'setting the type of parameter to 'unknown' : typeguarding in typecript

I have a function that I use towards typeguarding a data object from fixtue file-

export function isValidRouteAndPassenger(data: unknown): data is RouteAndPassenger {
  if (typeof data !== 'object' || data === null || data === undefined) {
    throw new Error(`routeAndPassenger object is not valid`);
  }
  return data.route && data.passenger;
}

error - Property 'route' does not exist on type 'object'.

this is the interface I use as type-

export interface RouteAndPassenger {
  route: Route;
  passenger: Passenger;
}

and the fixture file-

{
  "route": {
    "name": "Reykjavík"
  },
  "passenger": {
    "name": "Joaquin",
    "boardingWaypointName": "Buckingham Palace",
    "disembarkingWaypointName": "Royal Pavilion"
  }
}

wondering how i could fix the error. any ideas please?



Solution 1:[1]

Typescript won't let you access .data and .passenger until you first prove that those properties exist. It's true that you're only accessing them in order to show that they're there, but typescript still won't let you do that. Instead, you can check for the properties using the in operator:

export function isValidRouteAndPassenger(data: unknown): data is RouteAndPassenger {
  if (typeof data !== 'object' || data === null || data === undefined) {
    throw new Error(`routeAndPassenger object is not valid`);
  }
  return "route" in data && "passenger" in data;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Tower