Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from inferred parameters tuple

Tags:

typescript

If I have:

const selector = (state: {}, count = 1) => {};
type parms = Parameters<typeof selector>;

then parms will be:

[{}, number?]

I note if I apply an index I can extract a single param:

type parms = Parameters<typeof selector>[1]; // type parms = number

Is there some way to indicate I would like to omit the first parameter from being returned? Something along the lines of .slice(1)?

like image 937
Mister Epic Avatar asked Mar 25 '19 18:03

Mister Epic


1 Answers

For the specific case of "remove the first element from a tuple", you can use variadic tuple types as introduced in TypeScript 4.0:

type Tail<T extends any[]> = T extends [infer A, ...infer R] ? R : never;

Before 4.0 you could do it with generic rest parameters:

type Tail<T extends any[]> = 
  ((...x: T) => void) extends ((h: infer A, ...t: infer R) => void) ? R : never;

Either way gives you the desired behavior:

type Test = Tail<[1,2,3,4,5]>; // [2,3,4,5]
type Parms = Tail<Parameters<typeof selector>>; // [number?]

Playground link to code

like image 112
jcalz Avatar answered Oct 28 '22 15:10

jcalz