Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Created February 3, 2024 02:52
Show Gist options
  • Save ryangoree/eec579fdf6cdb79220c7206b0232e768 to your computer and use it in GitHub Desktop.
Save ryangoree/eec579fdf6cdb79220c7206b0232e768 to your computer and use it in GitHub Desktop.
ByIndex
/**
* 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