Acid Coder
Acid Coder

Reputation: 2747

Typescript check whether a type is tuple or array

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

Upvotes: 2

Views: 305

Answers (2)

Tobias S.
Tobias S.

Reputation: 23825

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

Upvotes: 3

Acid Coder
Acid Coder

Reputation: 2747

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

Upvotes: 2

Related Questions