TypeScript函数类型定义:如何根据对象字段返回对应类型结果
TypeScript函数类型定义:根据输入字段名返回对应类型属性
你的需求是创建一个函数,接收myObjectType的字段名,返回包含该字段对应类型属性的对象。之前的写法报错是因为无法在返回类型中直接使用参数名来索引类型,需要用泛型来关联输入参数和返回类型的关系。
正确的类型定义写法
type myObjectType = { field1: string, field2: number } // 用泛型K约束为myObjectType的键类型 type GenerateMyElement = <K extends keyof myObjectType>( name: K ) => { attr1: string, attr2: string, value: myObjectType[K] }
对应的函数实现示例
const myObject: myObjectType = { field1: 'string', field2: 0 } // 给函数标注类型,或让TS自动推断 const generateMyElement: GenerateMyElement = (field) => { return { attr1: 'val1', attr2: 'val2', value: myObject[field] } } // 调用示例,TS会自动推断value的类型 const elem1 = generateMyElement('field1') // elem1.value类型为string const elem2 = generateMyElement('field2') // elem2.value类型为number
为什么这样写能解决问题
- 泛型参数
K被约束为keyof myObjectType,确保传入的name只能是myObjectType的合法字段名。 - 返回类型中的
myObjectType[K]会根据K的具体值动态确定类型,实现了输入参数和返回类型的关联,TypeScript可以准确推断返回值中value的类型。
内容的提问来源于stack exchange,提问作者Dimitris Ragousis
相关产品推荐
相关产品推荐

