如何声明TypeScript函数返回指定接口命名属性的对应类型
TypeScript 传入属性名自动匹配对应返回类型实现方案
这个需求完全可以实现,只需为函数添加泛型约束即可。
原写法问题说明
你当前的代码中,name参数的类型为keyof FooInterface,也就是"x" | "y"的联合类型,对应的返回值会被TypeScript推导为number | string的联合类型,无法根据传入的具体key值自动收窄到对应属性的类型。
修复方案
针对固定接口的实现
直接为函数添加泛型约束,绑定传入的key类型和返回值类型:
interface FooInterface { x: number; y: string; } // 泛型K约束为FooInterface的合法键,返回值类型用索引访问类型FooInterface[K]声明 function fooFunction<K extends keyof FooInterface>(data: FooInterface, name: K): FooInterface[K] { return data[name]; } let fooVar = fooFunction({ x: 123, y: "hello" }, "x"); // 此时fooVar类型会被自动识别为number let fooVar2 = fooFunction({ x: 123, y: "hello" }, "y"); // 此时fooVar2类型会被自动识别为string
通用任意对象适配实现
如果需要支持任意类型的对象,可再新增一层对象泛型,写为通用工具函数:
// 通用属性读取函数,适配任意对象类型 function getProperty<T, K extends keyof T>(data: T, name: K): T[K] { return data[name]; } // 测试用例 interface FooInterface { x: number; y: string; } const testData: FooInterface = { x: 123, y: "hello" }; let fooVar = getProperty(testData, "x"); // 类型为number let fooVar2 = getProperty(testData, "y"); // 类型为string
实现原理
这里用到了TypeScript的*索引访问类型(Indexed Access Types)*特性,T[K]语法可以直接获取到对象类型T上键K对应的属性类型,配合泛型的动态推导能力,就能自动匹配到传入key对应的返回值类型。
内容的提问来源于stack exchange,提问作者HelloWorld
相关产品推荐
相关产品推荐

