Skip to content

Instantly share code, notes, and snippets.

@oneillci
Created January 30, 2018 11:13
Show Gist options
  • Save oneillci/50996d36a027a7932a5543a1d7742fa3 to your computer and use it in GitHub Desktop.
Save oneillci/50996d36a027a7932a5543a1d7742fa3 to your computer and use it in GitHub Desktop.
interface Person {
name: string;
age: number;
location: string;
}
type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person }; // string
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key]; // Inferred type is T[K]
}
function getKey<T, K extends keyof T>(obj: T, key: K) {
const x = obj[key];
return key; // Inferred type is T[K]
}
const nameof = <T>(name: keyof T) => name;
let x: Person = { name: "hello!", age: 20, location: "syd" };
console.log(getProperty(x, "name"));
console.log(getKey(x, "yo"));
console.log(nameof<Person>("name"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment