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[] });
关键修改说明
- 补充运行时判断参数:新增
targetEntityType参数,类型约束为T['entityType']——这个参数是运行时存在的实际字符串值,替代原代码中无法访问的T.entityType类型。 - 实现自动类型推断:当传入具体的实体类型字符串(如
'Type_A')时,TypeScript会自动推断泛型T对应TypeA,进而让函数返回TypeA[]类型,无需手动指定泛型。 - 修正类型守卫逻辑:用传入的
targetEntityType值做判断,确保运行时逻辑与类型断言的一致性。
内容的提问来源于stack exchange,提问作者Gerrol
相关产品推荐
相关产品推荐

