[英]TypeScript function that returns value for string literal of property name?
Consider this TypeScript function that returns the value of an objects property:考虑这个返回对象属性值的 TypeScript 函数:
export function getProperty<T>(object: T, key: string): any {
return (object as any)[key]
}
It is not very nice to use, since it always returns an any
:它不是很好用,因为它总是返回一个
any
:
interface Animal {
name: string,
hungry: boolean,
}
const myHippo: Animal = {
name: "Hippo",
hungry: true,
}
const name = getProperty(myHippo, "name") // Returns any, but I want a string.
const size = getProperty(myHippo, "size") // Returns any, but I want a compiler error.
I would like it to return a value with the correct type, eg string
for "name"
, and cause a compiler error if the string literal provided in key
is not a property of object
.我想这是正确类型返回一个值,例如
string
为"name"
,并导致编译错误,如果提供的字符串字面key
是没有的属性object
。 (I do not need to support non literal strings, those can be compiler errors too.) (我不需要支持非文字字符串,那些也可能是编译器错误。)
Is this even possible with TypeScript?这甚至可以用 TypeScript 实现吗? I suspect not, but I am not sure.
我怀疑不是,但我不确定。
Something that would be useful as a step in the right direction would be an utility type Keys<T>
that represent the union of all string literals that are property names in T
.作为朝着正确方向迈出的一步,有用的东西是实用程序类型
Keys<T>
,它表示作为T
中属性名称的所有字符串文字的联合。 But that doesn't seem to exist?但这似乎并不存在?
export function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
This gives you the compiler failure you want and the return type matches the property type这为您提供了所需的编译器失败,并且返回类型与属性类型匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.