Skip to content

Instantly share code, notes, and snippets.

@misha-erm
Last active May 20, 2021 10:06
Show Gist options
  • Save misha-erm/c855c4e1342eadbf16ac9479d6cbeaac to your computer and use it in GitHub Desktop.
Save misha-erm/c855c4e1342eadbf16ac9479d6cbeaac to your computer and use it in GitHub Desktop.
How to key ReadonlyArray type by 'id' key?
/*
*
* I want to key array by 'id'
*
* FROM: [{id: 'a', name: 'A'}, {id: 'b', name: 'B'}]
* TO: { a: {id: 'a', name: 'A'}, b: {id: 'b', name: 'B'} }
*
*/
const arr = [{id: 'a', name: 'A'}, {id: 'b', name: 'B'}] as const
type Arr = typeof arr;
type K = Extract<keyof Arr, number>;
type KeyBy<Arr extends ReadonlyArray<{id: string, name: string}>> = {
[K in Arr[number]['id']]: Extract<Arr[number], {id: K}>
}
type Res = KeyBy<Arr>
const a: Res = {
a: {id: 'a', name: 'A'},
b: {id: 'b', name: 'B'}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment