代码之家  ›  专栏  ›  技术社区  ›  Alyona

Typescript,如何通过道具过滤后重新分配类型?

  •  1
  • Alyona  · 技术社区  · 2 年前

    我有一个数组,其中包含:

    const list: Readonly<ListProps> = {some values}
    
    interface ListProps {
      type: 'radio' | 'check';
      style: 'text' | 'button';
      options: OptionProps[];
    }
    
    interface OptionProps {
      label: string;
      value: string;
      sublist?: ListProps;
    }
    

    我过滤掉了 options 只留下那些 sublist :

    const nodesWithSublist: ListNodeWithSublist[] = list.options.filter(
        (style: OptionProps) => style.sublist,
      );
    interface ListNodeWithSublist {
      label: string;
      value: string;
      sublist: ListProps;
    }
    

    我说错了 OptionProps[] 无法分配给 ListNodeWithSublist[] 因为 子列表 不可能 undefined 。但由于我过滤了结果,使其仅具有具有 子列表 ,我认为将数组分配给是正确的 ListNodeWithSublist 。如何处理?

    1 回复  |  直到 2 年前
        1
  •  2
  •   T.J. Crowder    2 年前

    不幸的是,这是TypeScript目前的限制,请参阅 issue #42384 ,这是对新行为的建议:

    若在对象的属性上检查了类型保护,则Typescript应该能够推断对象的类型。目前,Typescript确实正确地推断了属性的类型,但没有正确地推断其父对象的类型。

    在实现之前/除非实现,否则您可以定义自己的 type predicate 相反:

    function hasSublist(option: OptionProps): option is ListNodeWithSublist {
        return typeof option.sublist !== "undefined";
    }
    

    …,然后在该代码中使用它(这也意味着可以省略类型注释,因为它是从 filter ):

    const nodesWithSublist = list.options.filter(hasSublist);
    

    Playground link

    推荐文章