Skip to content

Instantly share code, notes, and snippets.

@drewwiens
Created November 16, 2020 16:34
Show Gist options
  • Save drewwiens/3d9e3e08d90023e77bd8b411e357ba3f to your computer and use it in GitHub Desktop.
Save drewwiens/3d9e3e08d90023e77bd8b411e357ba3f to your computer and use it in GitHub Desktop.
Random useful TypeScript code snippets
/*
Ever need just the keys of an interface who's values match a certain type? e.g.
interface A {
id: string;
other: boolean:
}
we want a union of the keys of the properties with a value of type string (useful for strongly typing a mapping arrays of objects, to hashmap with a specific key value to be used as key in hashmap)
*/
type Unionize<T extends object> = {
[k in keyof T]: {k: k; v: T[k]}
}[keyof T];
type PickKeysWithTypeV<T extends object, V> =
Extract<Unionize<T>, {v: V}>['k'];
function mapFromArray<T extends {}>(array: T[], propName: PickKeysWithTypeV<T, PropertyKey>) {
return array.reduce((prev, curr: T) => {
const key = curr[propName];
prev.set(key, curr);
return prev;
}, new Map<T[PickKeysWithTypeV<T, PropertyKey>], T>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment