Home > other >  Typescript check whether a type is tuple or array
Typescript check whether a type is tuple or array

Time:07-22

type A = [1, 2, 3]
type B = (1|2|3)[]

type IsTuple<T> = ???

type C = IsTuple<A> // true
type D = IsTuple<B> // false

I am looking for a way to tell tuple and array type apart

CodePudding user response:

This is the method I always use:

type IsTuple<T> = T extends [any, ...any] ? true : false

We can basically check if there are individual elements inside the tuple.

Playground

CodePudding user response:

update, I figured out the answer, by checking the length

type A = [1, 2, 3]
type B = (1|2|3)[]

type C = A['length'] //3
type D = B['length'] // number

playground

  • Related