我有this playground的这段代码
export interface Page {
heading: string;
component: string;
path: string;
}
export type RouteOnly = Pick<Page, 'heading' | 'path'>;
export const routes: (Page | RouteOnly)[] = [
{
heading: 'Home',
path: '/home',
component: 'A',
},
{
heading: 'OSS',
path: '/oss',
component: 'B',
},
{
heading: 'CV',
path: '/cv'
}
];
export function isPage(pageOrRoute: Page | RouteOnly): pageOrRoute is Page {
return !!(pageOrRoute as Page).component;
}
const pages: Page[] = routes.filter((r) => isPage(r));
我本以为ts知道pages
数组仅包含页面,但是ts抱怨:
“ Pick”类型缺少属性“ component”,但在“ Page”类型中必需
答案 0 :(得分:1)
我会做这样的事情:
export interface RouteOnly {
path: string;
heading: string;
}
// type Page = RouteOnly & { component: string };
export interface Page extends RouteOnly {
component: string;
}
export const routes: (Page | RouteOnly)[] = [
{
heading: 'Home',
path: '/home',
component: 'A',
},
{
heading: 'OSS',
path: '/oss',
component: 'B',
},
{
heading: 'CV',
path: '/cv'
}
];
export function isPage(arg: unknown): arg is Page {
return ({}).hasOwnProperty.call(arg || '', 'component');
}
const pages: Page[] = routes.filter(isPage);