缩小typescript中的联合类型

缩小typescript中的联合类型,typescript,Typescript,我有以下代码: export async function loadInitialProps(routes: AsyncRouteProps[], pathname: string, ctx: any): Promise<InitialProps> { const promises: Promise<any>[] = []; const match = routes.find((route: AsyncRouteProps) => { const

我有以下代码:

export async function loadInitialProps(routes: AsyncRouteProps[], pathname: string, ctx: any): Promise<InitialProps> {
  const promises: Promise<any>[] = [];

  const match = routes.find((route: AsyncRouteProps) => {
    const matched = matchPath(pathname, route);

    if (matched && route.component && isAsyncComponent(route.component)) {
      promises.push(
        route.component.load
          ? route.component.load().then(() => route.component.getInitialProps({ matched, ...ctx }))
          : route.component.getInitialProps({ matched, ...ctx })
      );
    }

    return !!matched;
  });

  return {
    match,
    data: (await Promise.all(promises))[0]
  };
}
My
AsyncRouteableComponent
类型是联合类型:

export type AsyncRouteableComponent<Props = any> =
  | AsyncRouteComponentType<RouteComponentProps<Props>>
  | React.ComponentType<RouteComponentProps<Props>>
  | React.ComponentType<Props>;
我收到错误消息:

类型上不存在属性“getInitialProps”
“AsyncRouteableComponent”。属性“getInitialProps”不存在
存在于类型“ComponentClass”上。
因此,在我的保护条款之后,它似乎没有缩小范围

我可以通过这样做来修复它,但我认为guard功能意味着我不需要这样做:

if (matched && route.component && isAsyncComponent(route.component)) {
  const component = route.component as AsyncRouteComponentType<any>;

  promises.push(
    component.load
      ? component.load().then(() => component.getInitialProps({ matched, ...ctx }))
      : component.getInitialProps({ matched, ...ctx })
  );
}
if(匹配的&route.component&&isAsyncComponent(route.component)){
const component=route.component作为AsyncRouteComponentType;
承诺,推动(
组件负载
?component.load().然后(()=>component.getInitialProps({matched,…ctx}))
:component.getInitialProps({matched,…ctx})
);
}

可变局部变量(如
route
)的收缩不适用于回调(如
then
回调)内部,因为TypeScript不相信在回调执行之前不会重新分配局部变量。有关更多信息,请参阅。解决方法是在调用guard函数之前,将
route
(或
route.component
)复制到
const
变量中

if (matched && route.component && isAsyncComponent(route.component)) {
  promises.push(
    route.component.load
      ? route.component.load().then(() => route.component.getInitialProps({ matched, ...ctx }))
      : route.component.getInitialProps({ matched, ...ctx })
  );
}
Property 'getInitialProps' does not exist on type
'AsyncRouteableComponent<any>'.   Property 'getInitialProps' does not
exist on type 'ComponentClass<RouteComponentProps<any,
StaticContext>>'.
if (matched && route.component && isAsyncComponent(route.component)) {
  const component = route.component as AsyncRouteComponentType<any>;

  promises.push(
    component.load
      ? component.load().then(() => component.getInitialProps({ matched, ...ctx }))
      : component.getInitialProps({ matched, ...ctx })
  );
}