Created
October 12, 2023 21:47
-
-
Save lotus128/0c276cf653c13009e525b3ec42f885cf to your computer and use it in GitHub Desktop.
Lab, TypeScript mapped types: select from Record with order
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
| function pickValueOfRecordUsingOrder< | |
| TKey extends PropertyKey, | |
| const TOrder extends ReadonlyArray<TKey>, | |
| const TInputRecord extends Record<TOrder[number], number>, | |
| TResultArray extends { | |
| [X in keyof TOrder]: TInputRecord[TOrder[X]] // any value can be selected | |
| }, | |
| >( | |
| input: TInputRecord, | |
| order: TOrder | |
| ): TResultArray { | |
| } | |
| // [1, 9, 2, 1, 6, 8, 1, 1] | |
| const result1 = pickValueOfRecordUsingOrder( | |
| { | |
| 'a': 1, | |
| 'b': 2, | |
| 'c': 3, | |
| 'd': 4, | |
| 'e': 5, | |
| 'f': 6, | |
| 'g': 7, | |
| 'h': 8, | |
| 'i': 9, | |
| 'j': 10, | |
| 'k': 11, | |
| 'l': 12, | |
| 'm': 13, | |
| 'n': 14, | |
| 'o': 15, | |
| 'p': 16, | |
| 'q': 17, | |
| 'r': 18, | |
| 's': 19, | |
| 't': 20, | |
| 'u': 21, | |
| 'v': 22, | |
| 'w': 23, | |
| 'x': 24, | |
| 'y': 25, | |
| 'z': 26, | |
| } as const, | |
| [ | |
| 'a', | |
| 'i', | |
| 'b', | |
| 'a', | |
| 'f', | |
| 'h', | |
| 'a', | |
| 'a' | |
| ] as const | |
| ) | |
| interface HasGetValue<T> { | |
| getValue: () => T | |
| } | |
| function pickPropertyFromValueOfRecordUsingOrder< | |
| TKey extends PropertyKey, | |
| const TOrder extends ReadonlyArray<TKey>, | |
| const TInputRecord extends Record<TOrder[number], HasGetValue<unknown>>, | |
| TResultArray extends { | |
| [X in keyof TOrder]: ReturnType<TInputRecord[TOrder[X]]['getValue']> // any value can be selected | |
| }, | |
| >( | |
| input: TInputRecord, | |
| order: TOrder | |
| ): TResultArray { | |
| } | |
| // [1, 9, 2, 1, 6, 8, 1, 1] | |
| const result2 = pickPropertyFromValueOfRecordUsingOrder( | |
| { | |
| 'a': { | |
| getValue: () => '1' | |
| }, | |
| 'b': { | |
| getValue: () => '2' | |
| }, | |
| 'f': { | |
| getValue: () => '6' | |
| }, | |
| 'h': { | |
| getValue: () => '8' | |
| }, | |
| 'i': { | |
| getValue: () => '9' | |
| }, | |
| } as const, | |
| [ | |
| 'a', | |
| 'i', | |
| 'b', | |
| 'a', | |
| 'f', | |
| 'h', | |
| 'a', | |
| 'a' | |
| ] as const | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment