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

基于泛型数组参数扩展TypeScript类型的问题

解决方案

核心问题:正确检查泛型数组中的关键词

你原来的判断逻辑K extends 'totals'[]不生效,是因为K是多元素元组类型(比如['totals', 'body']),不可能等于单一元素的数组类型。正确的方式是判断指定关键词是否属于数组的元素集合,用'totals' extends K[number]语法:

type Keywords = 'totals' | 'body'  // ...and more

type Model<K extends Keywords[] = []> = {
  id: number
} 
& ('totals' extends K[number] ? {total: number, amount: number} : {})
& ('body' extends K[number] ? {body: string, name: string} : {})

// 此时TypeScript会正确提示缺少total、amount、body、name属性
const m: Model<['totals', 'body']> = {id: 1}  

只要K数组中包含对应关键词,就会自动合并对应的属性,多关键词组合也能正常生效。

次要问题:让变量类型精确匹配实际赋值的关键词

默认Keywords[]是宽松的数组类型,无法精确代表具体的关键词集合。要让words的类型锁定为实际赋值的元组,需要使用as const断言:

// words的类型变为readonly ['totals'],而非宽泛的Keywords[]
const words = ['totals'] as const  

// 直接传入泛型时,需将元组转为数组类型
type NewModel = Model<typeof words[number][]>

如果想简化泛型使用,可以调整Model的泛型参数为元素类型而非数组类型,这样代码更简洁:

type Model<K extends Keywords = never> = {
  id: number
} 
& (K extends 'totals' ? {total: number, amount: number} : {})
& (K extends 'body' ? {body: string, name: string} : {})

const words = ['totals'] as const  
type NewModel = Model<typeof words[number]>
// NewModel会包含id、total、amount三个属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:42:40