Last active
May 20, 2021 10:06
-
-
Save misha-erm/c855c4e1342eadbf16ac9479d6cbeaac to your computer and use it in GitHub Desktop.
How to key ReadonlyArray type by 'id' key?
This file contains hidden or 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
/* | |
* | |
* 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