2

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!

1 Answer 1

7

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!");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

instanceof Array fails when checking arrays across frames. Prefer Array.isArray: twitter.com/mgechev/status/1292709820873748480

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.