You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中通过联合类型过滤对象数组?

当然可以实现,核心是要把TypeScript的编译时类型和运行时逻辑结合起来:

因为TypeScript的类型信息在编译后会被完全擦除,没法直接用NamesType这个类型去过滤数组,得先把类型对应的实际值转换成运行时能用到的集合,再配合类型断言或类型谓词让TS正确推断结果类型。

具体步骤:

  • 第一步:把联合类型的取值存成运行时数组
    先定义一个包含NamesType所有取值的常量数组,用as const锁定它的类型为字面量集合:

    const array = [{name: 'something'}, {name: 'random'}, {name: 'bob'}];
    type NamesType = 'something' | 'bob';
    const allowedNames = ['something', 'bob'] as const;
    
  • 第二步:过滤数组并修正类型
    用数组的filter方法配合类型谓词,既完成运行时过滤,又让TypeScript识别出过滤后数组的正确类型:

    // 类型谓函数,告诉TS符合条件的元素属于目标类型
    function isAllowedItem(item: {name: string}): item is {name: NamesType} {
      return (allowedNames as readonly string[]).includes(item.name);
    }
    
    const filteredArray = array.filter(isAllowedItem);
    // 此时filteredArray的类型是Array<{name: NamesType}>,值正好是[{name: 'something'}, {name: 'bob'}]
    

    如果想写得更简洁,也可以直接用类型断言省略单独的谓函数:

    const filteredArray = array.filter(item => 
      (allowedNames as readonly string[]).includes(item.name)
    ) as Array<{name: NamesType}>;
    

内容的提问来源于stack exchange,提问作者rbrtj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:11:03