abagshaw abagshaw - 3 months ago 22
TypeScript Question

How to check if variable is a tuple in TypeScript

I am trying to see if a variable passed to a function (that can be either an array of numbers or an array of tuples) is the array of tuples.

function (times: Array<number> | Array<[number, number]>) {
if (times[0] instanceof [number, number]) {
console.log("Its the tuple one!");
}
}


The above code doesn't work though and I've also tried
if (times[0] instanceof tuple))
but that doesn't work either. How can this be done?

Thanks!

Answer

According to the Basic Types > Tuple docs:

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.

Meaning that tuples are just arrays.
Also, as typescript compiles to javascript, and javascript doesn't have tuples, then checking for the type at runtime means that you need to check against javascript types and not ts types that don't exist at runtime.

To answer your question:

function fn(times: Array<number> | Array<[number, number]>) {
    if (times[0] instanceof Array) {
        console.log("Its the tuple one!");
    }
}