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

如何约束泛型对象中值为字符串的键作为类型参数?

如何约束TypeScript接口的键为对象中值类型为字符串的属性?

你可以通过条件类型筛选出T中值类型为string的键,修改MyInterface的泛型约束来实现需求。

方案一:直接在泛型约束中定义

修改后的接口如下:

interface MyInterface<T, K extends keyof T & (T[K] extends string ? K : never)> {
  key: K
  data: Array<T>
}

方案二:先定义工具类型(更易读)

先封装一个工具类型,专门提取对象中值为字符串类型的键:

// 工具类型:提取T中值类型为string的键
type StringKeys<T> = { [P in keyof T]: T[P] extends string ? P : never }[keyof T]

interface MyInterface<T, K extends StringKeys<T>> {
  key: K
  data: Array<T>
}

验证效果

用你提供的Data接口测试:

interface Data {
  foo: string
  bar: number
}

const d: Data[] = [{ foo: 'xxx', bar: 1 }]

// 合法:key是Data中值为string的键
const a: MyInterface<Data, 'foo'> = { key: 'foo', data: d }

// 触发类型错误:bar对应值为number,不符合约束
const b: MyInterface<Data, 'bar'> = { key: 'bar', data: d } 

// 触发类型错误:baz不是Data的键
const c: MyInterface<Data, 'baz'> = { key: 'baz', data: d }

原理说明

  • StringKeys<T>通过映射类型遍历T的所有键,对每个键P判断T[P]是否为string:如果是则保留该键,否则返回never。
  • 最后通过[keyof T]提取出所有符合条件的键,形成一个联合类型,这样K就只能是这些键的子集,同时自动满足属于keyof T的约束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:20:26