Open AlCalzone opened 6 years ago
I just ran into this issue myself and wanted to throw in my two cents about the syntax for how this would behave. Considering how this inference is written for function types and how rest elements of tuples are constructed:
type Tail<T> = T extends (head: any, ...tail: infer U) ? U : never;
type Rest = string[];
type Tuple = [any, ...Rest];
I would suggest the following syntax:
type Tail<T> = T extends [any, ...infer U] ? U : never;
The current workaround:
type Tail<T extends any[]> = ((...args: T) => any) extends ((
_: infer First,
...rest: infer Rest
) => any)
? T extends any[] ? Rest : ReadonlyArray<Rest[number]>
: []
Note: Does not work in TypeScript 2.9.x and under.
@AlCalzone - Thanks for the examples FirstArg
and RestArgs
. They inspired these additional examples:
export type Length<T extends any[]> = T extends (infer U)[] & { length: infer L } ? L : never;
export type LengthMinusOne<T extends any[]> = Length<Tail<T>>;
export type LengthPlusOne<T extends any[]> = Length<Cons<any, T>>;
export type Last<T extends any[]> = T[LengthMinusOne<T>];
// Example:
// export type TestLastType = Last<[boolean, string, number]>; //number
Based on the above, it would be great to have something like:
type Last<T extends any[]> = T extends [...any[], infer L] ? L : never;
type Tail<A extends any[]> =
((...args: A) => any) extends ((h: any, ...t: infer T) => any) ? T : never
This works in TypeScript v4 (via variadic tuple types):
type Tail<T extends any[]> = T extends [any, ...infer U] ? U : never;
This seems like it can probably be closed, given the snippet shown above?
Not sure that works but I might be missing something here. For example
type Tail<T extends any[]> = T extends [any, ...infer U] ? U : never;
const xs = ["1", "2", "3"];
type T = Tail<typeof xs>; // never
@futtetennista It fails in your example because typeof xs
is not a tuple type (it's string[]
). Here is an updated version that works:
const xs = ["1", "2", "3"] as const
type Xs = typeof xs
type Tail<T extends readonly any[]> = T extends readonly [any, ...infer U] ? U : never;
type TT = Tail<Xs>
Search Terms
rest element infer tuple
Suggestion
Currently, inferring single elements of tuple types is possible using the
infer
keyword:However it is not possible to infer the type of the remaining arguments in one go, except by resorting to functions:
I would like to see the possibility to infer rest types in tuples, e.g. like this (square brackets):
or like this (3 dots)
Checklist
My suggestion meets these guidelines: