-
-
Save blemoine/fc74855d88bedbd12855ed1460f6335d to your computer and use it in GitHub Desktop.
This file contains 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
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