我有一个函数用于从固定文件中保护数据对象-
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'.
这是我使用的接口类型-
export interface RouteAndPassenger {
route: Route;
passenger: Passenger;
}
和fixture文件-
{
"route": {
"name": "Reykjavík"
},
"passenger": {
"name": "Joaquin",
"boardingWaypointName": "Buckingham Palace",
"disembarkingWaypointName": "Royal Pavilion"
}
}
想知道如何修复错误。有什么想法吗?
Typescript不会让你访问.data
和.passenger
,直到你首先证明这些属性存在。的确,你访问它们只是为了显示它们在那里,但typescript仍然不允许你这样做。相反,您可以使用in操作符检查属性:
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;
}