Created
October 16, 2019 10:51
-
-
Save DannyMoerkerke/2d1eebcb0da1d87f3164b528aa9e366c to your computer and use it in GitHub Desktop.
A typesafe curried getter
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
// HasKey checks whether the given object has the specified key 'K' | |
type HasKey<K extends string, V = unknown> = {[_ in K]: V}; | |
// curried getter | |
const get = <K extends string, O extends HasKey<K>>(key: K) => (obj: O): O[K] => obj[key]; | |
// the object to check | |
const Person = {name: 'Danny', age: '47'}; | |
const getAge = get('age'); | |
getAge(Person); // ok, Person has key 'age' | |
const getAddress = get('address'); | |
getAddress(Person); // error, Person has no key 'address' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment