Guide on verifying if a variable is a tuple in TypeScript

I am attempting to determine if a variable passed to a function, which can either be an array of numbers or an array of tuples, is the array of tuples.

function (times: Array<number> | Array<[number, number]>) {
    if (Array.isArray(times[0]) && times[0].length === 2 && typeof times[0][0] === 'number' && typeof times[0][1] === 'number') {
        console.log("It's the tuple one!");
    }
}

The code above is not functioning as expected. I have also attempted using if (times[0] instanceof tuple)), but that did not work either. Is there a way to achieve this?

Thank you!

Answer №1

As per the Tuple section of Basic Types documentation:

Tuple types enable you to define an array where a specific number of elements have known types, but those types do not necessarily have to be identical.

This implies that tuples essentially function like arrays.
Furthermore, since typescript translates to javascript and javascript does not support tuples, verifying the type during runtime requires cross-referencing with javascript types rather than typescript ones which are non-existent during runtime.

To address your query:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only filter the array by its value if the value is specified

Is there a way to apply this filter while only checking each condition if the value is not undefined? For instance, if taxId is undefined, I would like to skip it rather than using it as a filter criterion. this.subAgencies = demoSubAgencies.filter(fun ...

Using optional chaining with TypeScript types

I'm dealing with a complex data structure that is deeply nested, and I need to reference a type within it. The issue is that this type doesn't have its own unique name or definition. Here's an example: MyQuery['system']['error ...

Steps for transferring data between two components

I'm looking for a way to transfer an object's id from one component to another. <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let user"> ...

Is there a way to merge two observables into one observable when returning them?

I'm struggling with getting a function to properly return. There's a condition where I want it to return an Observable, and another condition where I'd like it to return the combined results of two observables. Here is an example. getSearc ...

Having trouble viewing the initial value in an AngularJS2 inputText field

I'm having trouble displaying the initial value in inputText. I'm unsure of what mistake I'm making, but the value should be showing up as expected. Kind regards, Alper <input type="text" value="1" [(ngModel)]="Input.VSAT_input1" name= ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Upon executing the tsd install and tsd query commands, a message indicating 'no results found' was displayed

Whenever I run these commands in Git Bash on Windows tsd query angular-material tsd query angular tsd install angular angular-material I always receive the message ">> zero results" ...

Inquiry regarding Typescript's array of types

While researching how to declare arrays of types online, I came across the following example: arrayVar: Array<Type> Seems simple enough, so I attempted to declare my variable like this: transactions: Transactions = { total : 0, list: Array<Transa ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

Creating a TypeScript array of objects that aligns with a specific interface: A step-by-step guide

In the code snippet below, there is a Typescript interface called Product. The goal is to ensure that every object in the products array follows this interface. However, the implementation process has been challenging so far. Various attempts like products ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Error encountered in Angular/Ramda while using mapAccum with an array of objects in Typescript

I am having difficulties implementing Ramda in an Angular 6 / TypeScript environment. "ramda": "^0.25.0", "@types/ramda": "^0.25.24" This is how I have started: const addP = (p1,p2) => ({ x: p1.x+p2.x,y: p1.y+p2.y }); const accum = (a,b) => [add ...

The default behavior of Angular-Keycloak does not include automatically attaching the bearer token to my http requests

I'm currently working on integrating keycloak-angular into my project, but I'm facing an issue with setting the bearer token as the default for my HTTP requests. "keycloak-angular": "9.1.0" "keycloak-js": "16.0 ...

Promise rejection not handled: The play() function was unsuccessful as it requires the user to interact with the document beforehand

After upgrading my application from Angular 10 to 11, I encountered an error while running unit tests. The error causes the tests to terminate, but strangely, sometimes they run without any issues. Does anyone have suggestions on how to resolve this issue? ...

Error display in Elastic Apm Rum Angular implementation

Having some issues with incorporating the @elastic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5948598d8878098d8949b9280999487b5c7dbc4dbc4">[email protected]</a> package into my project. Angular is throwing console ...

Inferencing partial types in Typescript

I'm completely stuck on this and can't seem to figure it out without using a second function: interface Fixed { a: number } const fn = <A, B extends {} = {}>(b: B) => { return b } fn({ a: 1 }) // { a: number } fn<Fixed>({ a: 1 } ...

Is there a way to achieve a seamless compilation in TypeScript?

Hopefully this is straightforward! TypeScript Latest version: 1.9.0-dev.20160512 (can be installed using npm install -g typescript@next as suggested by @basarat) Node v5.11.0 Windows 10.0.10586 First file: u1c.ts import * as u1u from "./u1u.ts" let p = ...