Home > Mobile >  Typescript tuple: first item is function and parameter are rest of tuple
Typescript tuple: first item is function and parameter are rest of tuple

Time:11-26


type Tuple = [];

const tup: Tuple = [
  ((a, b) = {
    //  a: number; tup 2th item
    //  b: boolean; tup 3th item
  }),
  1,
  false,
  // more item enble.
];

First item is a function, parameter type are rest of the tulpe.

i try defined the Tuple, but code error "Type alias 'Tuple' circularly references itself. "

type Tuple = [(...args: any) => void, ...Parameters<Tuple[0]>];

CodePudding user response:

It is generally not possible to write types where one part of the type is supposed to correlate with another (apart from pre defined unions and speciyfing an explicit generic type). You will need to create a generic function which is able to infer the type of the arguments.

const createTuple = <T extends any[]>(arg: [(...args: T) => void, ...T]) => arg

The elements in the tuple after the function will be inferred as T. We can then use T to type the parameters of the function.

const tuple = createTuple([
  (a, b) => {
    a
//  ^? a: number

    b
//  ^? b: boolean
  },
  1,
  false,
])

Playground

CodePudding user response:

Just define them separately.

type MyFunction = (a: number, b: boolean) => void;
type MyTuple = [MyFunction, ...Parameters<MyFunction>];
  • Related