Created
February 3, 2024 02:52
-
-
Save ryangoree/eec579fdf6cdb79220c7206b0232e768 to your computer and use it in GitHub Desktop.
ByIndex
This file contains 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
/** | |
* Converts array or tuple `T` to an object with keys as indices and values as element types. | |
* It's handy for when you need type-safe access based on indices, especially with tuples. | |
* | |
* `ByIndex` is useful over `{ [K in keyof T]: T[K] }` for: | |
* - Keeping index keys as strings for object mapping from tuples. | |
* - Handling arrays as tuples for a unified index-based object structure. | |
* | |
* Example: | |
* type ExampleTuple = ByIndex<[string, number]>; // { "0": string, "1": number } | |
* type ExampleArray = ByIndex<(string | number)[]>; // { [x: number]: string | number } | |
* | |
* It's a small utility that ensures your data structures remain type-safe, even with dynamic indexing. | |
*/ | |
type ByIndex<T extends any[]> = { | |
[K in keyof T as T extends [any, ...any[]] | |
? K extends `${number}` | |
? K | |
: never | |
: number]: K extends `${number}` | number ? T[K] : never; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment