Reputation: 8577
Consider this TypeScript function that returns the value of an objects property:
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
:
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, e.g. string
for "name"
, and cause a compiler error if the string literal provided in key
is not a property of object
. (I do not need to support non literal strings, those can be compiler errors too.)
Is this even possible with 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
. But that doesn't seem to exist?
Upvotes: 2
Views: 1076
Reputation: 426
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
Upvotes: 3