Home > front end >  Exclude specify index from Parameter type of function
Exclude specify index from Parameter type of function

Time:10-07

function fun1(a:number, b:string, c:()=>void)
{

}


function fun2(...args:Parameters<typeof fun1>)
{

}

I want exclude a specific index of fun1's parameters from function fun2's parameter types.

Basically the result should be:

function fun2(b:string, c:()=>void)
{

}

I tried using Omit<Parameters<typeof this._call>, "0"> but it doesn't work.

CodePudding user response:

The problem with using Omit is that it returns an object type rather than a tuple type (technically because Omit<T, U> is not a homomorphic mapping on T).

type Test = Omit<[0, 1], 0>
// type Test = {[x: number]: 0 | 1; [Symbol.iterator]: () => IterableIterator<0 | 1>; ...

To preserve the tuple type, you can declare a conditional type Tail that uses infer to obtain the the tail of T (kind of like pattern matching on the tuple structure):

type Tail<T extends readonly unknown[]> =
  T extends readonly [unknown, ...infer Rest] ? Rest : never

(The readonly's are required to also allow Tail to be used on read-only tuples.) You can use Tail like this:

function fun2(...args: Tail<Parameters<typeof fun1>>) {}
// function fun2(b: string, c: () => void): void

TypeScript playground

  • Related