如何在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; }
方案说明
- 核心逻辑:新增
LabelKey泛型参数,它既继承keyof ObjectType保证是ObjectType的合法属性名,又通过后续赋值给string类型变量的操作,让TypeScript自动约束ObjectType[LabelKey]必须为string类型。 - 完全匹配需求:
- 仅对
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
相关产品推荐
相关产品推荐

