如何为TypeScript值获取函数实现基于键的精确类型推导?
解决TypeScript值获取函数的精确类型推导问题
这个问题是TypeScript泛型场景里很常见的需求——想要让函数返回类型和传入的键做精准绑定,而不是返回一个宽泛的联合类型。咱们来一步步调整你的代码:
问题根源
你当前的ValueGetter类型把参数objectKey定义为keyof PInterface,返回值是PInterface[keyof PInterface],这会让TypeScript认为传入的键可能是任意的键类型,所以返回值只能是所有值类型的联合(string | string[]),没法做到精准推导。
修改后的实现方案
我们需要给函数添加一个具体的泛型参数来跟踪传入的键类型,而不是直接用keyof PInterface:
interface Person { name: string; favoriteColors: string[]; } const examplePerson: Person = { name: "Jack", favoriteColors: ["red", "blue"], } // 新增泛型K,约束为PInterface的键类型 type ValueGetter<PInterface> = <K extends keyof PInterface>( objectKey: K, objectValues: PInterface ) => PInterface[K]; const personValueGetter: ValueGetter<Person> = (objectKey, objectValues) => objectValues[objectKey];
验证效果
现在调用函数时,TypeScript会自动根据传入的键推导正确的返回类型:
- 调用
personValueGetter('name', examplePerson),返回类型精确为string - 调用
personValueGetter('favoriteColors', examplePerson),返回类型精确为string[]
可选优化:调整参数顺序
如果你习惯把对象放在前面(类似很多工具库的函数风格),可以调整参数顺序,泛型逻辑完全一致:
type ValueGetter<PInterface> = <K extends keyof PInterface>( objectValues: PInterface, objectKey: K ) => PInterface[K]; // 调用方式和你最开始的写法一致: personValueGetter(examplePerson, 'name'); // 返回类型为string
这样既符合你的调用习惯,又能保证类型的精准推导。
内容的提问来源于stack exchange,提问作者kmoney12
相关产品推荐
相关产品推荐

