I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.