如何在TypeScript中让泛型函数根据入参返回对应属性类型?
解决TypeScript泛型接口中getValue方法返回对应属性类型的问题
要实现调用getValue时根据传入的键返回对应属性的精确类型,需要将getValue方法本身定义为泛型方法,而非仅给外层接口I2添加泛型。
正确的接口定义
interface I2<T> { getValue<K extends keyof T>(arg0: K): T[K]; }
完整示例代码
// 定义原始数据接口 interface I1 { name: string, age: number } // 定义带泛型方法的访问接口 interface I2<T> { getValue<K extends keyof T>(key: K): T[K]; } // 实现I2<I1>的类 class Record implements I2<I1> { getValue<K extends keyof I1>(key: K): I1[K] { // 示例实现:从预设数据中取值 const data: I1 = { name: "Alice", age: 30 }; return data[key]; } } // 使用示例 const record: I2<I1> = new Record(); const name = record.getValue('name'); // 类型为string const age = record.getValue('age'); // 类型为number
原理说明
- 之前的写法中,
arg0是keyof T的联合类型,返回值T[keyof T]会变成所有属性类型的联合(比如string | number),无法对应到具体键的类型。 - 给
getValue添加泛型参数K并约束为keyof T后,TypeScript会根据传入的具体键值推断出K的字面量类型(比如传入'name'时,K就是'name'),进而返回T[K]对应的精确属性类型。
内容的提问来源于stack exchange,提问作者EliBaum
相关产品推荐
相关产品推荐

