Created
March 26, 2019 00:18
-
-
Save micahriggan/5f133189d33bdaec3ec7dfb6183808ad to your computer and use it in GitHub Desktop.
Example to show a typesafe way to log values from objects
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
/* given an object of type T, | |
* log the value of a property, specified by the argument key | |
*/ | |
function logValue<T>(obj: T, key: keyof T) { | |
console.log(obj[key]); | |
} | |
function simpleTest() { | |
const Micah = {name: 'Micah'}; | |
logValue(Micah, "name") | |
// The following would be invalid because "age" is not a key of Micah | |
// logValue(Micah, "age") | |
} | |
/* | |
* LOGS | |
* Micah | |
* | |
*/ | |
simpleTest(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment