Skip to content

Instantly share code, notes, and snippets.

@blemoine
Last active March 23, 2017 16:51
Show Gist options
  • Save blemoine/fc74855d88bedbd12855ed1460f6335d to your computer and use it in GitHub Desktop.
Save blemoine/fc74855d88bedbd12855ed1460f6335d to your computer and use it in GitHub Desktop.
function getProperty<A, P extends (keyof A) >(obj: A, prop: P): A[P] {
return obj[prop];
}
const user: User = {
firstName: "Georges",
lastName: "Abitbol",
age: 43
}
const name: string = getProperty(user, "firstName");
const age: number = getProperty(user, "age");
// The following doesn't compile
//Type 'string' is not assignable to type 'number'
const age: string = getProperty(user, "age");
//Argument of type '"name"' is not assignable to parameter of type '"firstName" | "lastName" | "age"'.
const name: string = getProperty(user, "name");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment