返回类型为的Typescript查找类型
如何根据作为param提供的键名来告诉typescript什么是返回类型:返回类型为的Typescript查找类型,typescript,Typescript,如何根据作为param提供的键名来告诉typescript什么是返回类型: type A = string type B = number type Data = { a: A, b: B } const getProp = (data: Data, key: keyof Data) => { return data[key] } const myData: Data = { a: 'foo', b: 123 } // Type 'strin
type A = string
type B = number
type Data = {
a: A,
b: B
}
const getProp = (data: Data, key: keyof Data) => {
return data[key]
}
const myData: Data = {
a: 'foo',
b: 123
}
// Type 'string | number' is not assignable to type 'string'.
// Type 'number' is not assignable to type 'string'.
^
const result: string = getProp(myData, 'a')
我知道我正在使用propa
,所以预期的返回类型是string。
我怎样才能让它工作呢?
您需要一个泛型类型:
const getProp=(数据:数据,键:K):数据[K]=>{
返回数据[键]
}
这是因为可以在调用站点将
K
推断为字符串文本类型'a'
(它扩展了keyofdata
),然后返回类型Data[K]
是Data['a']
,这是string
!实际上,我非常惊讶,在函数调用中,我不需要为typescript指定函数声明来理解返回类型。非常感谢。