Created
January 30, 2018 11:13
-
-
Save oneillci/50996d36a027a7932a5543a1d7742fa3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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