Home > OS >  Typescript generic with Tuple type
Typescript generic with Tuple type

Time:03-07

What I want is simple: I want to define a tuple type whose second argument is T[] if the first argument is determined to be T.

I can do this.

type TandTArray<T> = [T, T[]]

But, i had to specify every T enter image description here

But i want it to be determined by the first argument automatically.
I tried this But dosen't work

type TandTArray = <T>[T, T[]]

CodePudding user response:

You'll need a function for generic type to be inferred:

const tandTArray = <T>(x: [T, T[]]) => x;

const foo = tandTArray([1, [1]])

Playground

  • Related