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

如何在TypeScript中声明泛型函数约束单个属性为指定类型

简洁实现泛型函数约束指定属性为string类型

修正后的代码(兼容TypeScript 4.5.2)

function exampleFunction<ObjectType, LabelKey extends keyof ObjectType>(
  items: ObjectType[],
  labelProperty: LabelKey,
  uniqueIdentifierProperty: keyof ObjectType
): ObjectType[] {
  // TypeScript可自动推断该值为string类型,无类型报错
  const stringValue: string = items[0][labelProperty];
  return items;
}

方案说明

  1. 核心逻辑:新增LabelKey泛型参数,它既继承keyof ObjectType保证是ObjectType的合法属性名,又通过后续赋值给string类型变量的操作,让TypeScript自动约束ObjectType[LabelKey]必须为string类型。
  2. 完全匹配需求:
    • 仅对labelProperty指向的单个属性施加string约束,其他属性类型无任何限制;
    • 属性名通过keyof ObjectType动态传入,无需硬编码固定属性名;
    • 写法简洁直观,避免了复杂的泛型映射逻辑。

调用验证

原有的合法调用完全正常:

type Dog = { idNumeric: number; name: string; age: number; breed: string; };
type Car = { idString: string; manufacturer: string; year: number; model: string; };
const dogs: Dog[] = [{ idNumeric: 1, name: 'Fido', age: 5, breed: 'Labrador' }, { idNumeric: 2, name: 'Rex', age: 8, breed: 'Beagle' }];
const cars: Car[] = [{ idString: 'car1', manufacturer: 'Toyota', year: 2020, model: 'Camry' }, { idString: 'car2', manufacturer: 'Hyundai', year: 2021, model: 'Elantra' }];

exampleFunction(dogs, 'name', 'idNumeric'); // 合法
exampleFunction(cars, 'manufacturer', 'idString'); // 合法

若传入非string类型的属性作为labelProperty,TypeScript会直接抛出类型错误:

exampleFunction(dogs, 'idNumeric', 'name'); // 报错:Type 'number' is not assignable to type 'string'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:05:08