Skip to content

Instantly share code, notes, and snippets.

@webstrand
Created November 16, 2020 19:02
Show Gist options
  • Select an option

  • Save webstrand/89fd832a41b801e178ca0011868fa538 to your computer and use it in GitHub Desktop.

Select an option

Save webstrand/89fd832a41b801e178ca0011868fa538 to your computer and use it in GitHub Desktop.
Select the Nth member of a tuple, preserving optional and labels.
type Stump<N extends number, U extends readonly unknown[] = [], V extends readonly unknown[] = []> = N extends N ? number extends N ? readonly unknown[] : U["length"] extends N ? V : Stump<N, readonly [unknown, ...U], [unknown?, ...V]> : never;
type Truncate<T extends readonly unknown[]> = T extends [unknown?, ...infer U] ? T extends [...infer X, ...U] ? X : never : never;
type Select<T extends readonly unknown[], I extends keyof T & number> = Truncate<T extends readonly [...Stump<I>, ...infer U] ? U : []>;
type a = Select<[1,2,3], 1> // [2]
type b = Select<number[], 1> // [number?] // still doesn't work
type c = Select<[1,2?,3?], 1> // [2?]
type d = Select<[ foo: 1, bar?: 2 ], 1> // [ bar?: 2 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment