不能识别过滤数组的打字稿是类型为卫兵的一种

时间:2019-04-06 08:44:00

标签: typescript

我有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”类型中必需

1 个答案:

答案 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);