Skip to content

Instantly share code, notes, and snippets.

@DannyMoerkerke
Created October 16, 2019 10:51
Show Gist options
  • Save DannyMoerkerke/2d1eebcb0da1d87f3164b528aa9e366c to your computer and use it in GitHub Desktop.
Save DannyMoerkerke/2d1eebcb0da1d87f3164b528aa9e366c to your computer and use it in GitHub Desktop.
A typesafe curried getter
// 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