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

TypeScript泛型静态键取值:解决类型/值混用与自动推断问题

解决TypeScript类型过滤函数的类型推断问题

原代码的核心问题是泛型类型T仅存在于编译阶段,运行时无法直接访问T.entityType,这就导致了'T' only refers to a type, but is being used as a value here的错误。

以下是修正后的代码,同时实现自动类型推断:

type TypeA = {
  entityType: 'Type_A'
};

type TypeB = {
  entityType: 'Type_B'
};

type TypeAB = TypeA | TypeB;

// 调整函数:新增实体类型参数,用于运行时判断+类型推断
const getOnlySubTypeTInArray = <T extends TypeAB>(
  items: TypeAB[],
  targetEntityType: T['entityType']
) => items.filter(
  (item): item is T => item.entityType === targetEntityType,
);

const getTypeABs = (docs: TypeAB[]) : { typeAs: TypeA[], typeBs: TypeB[] } => ({
  typeAs: getOnlySubTypeTInArray(docs, 'Type_A'), // 自动推断返回TypeA[]
  typeBs: getOnlySubTypeTInArray(docs, 'Type_B'), // 自动推断返回TypeB[]
});

关键修改说明

  1. 补充运行时判断参数:新增targetEntityType参数,类型约束为T['entityType']——这个参数是运行时存在的实际字符串值,替代原代码中无法访问的T.entityType类型。
  2. 实现自动类型推断:当传入具体的实体类型字符串(如'Type_A')时,TypeScript会自动推断泛型T对应TypeA,进而让函数返回TypeA[]类型,无需手动指定泛型。
  3. 修正类型守卫逻辑:用传入的targetEntityType值做判断,确保运行时逻辑与类型断言的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:10:30