Is there a way to determine if a tuple is of infinite or finite length?

Is there a way to determine if a tuple is finite or infinite?

I've been working on a solution, but it doesn't cover all cases:

type IsFinite<T extends any[], Finite = true, Infinite = false> = T extends []
  ? Finite
  : T extends (infer Element)[]
  ? Element[] extends T
    ? Infinite
    : T extends [any, ...infer Rest]
    ? IsFinite<Rest, Finite, Infinite>
    : never
  : never

 type Foo1 = IsFinite<[string]>                          // true
 type Foo2 = IsFinite<[]>                                // true
 type Foo3 = IsFinite<string[]>                          // false
 type Foo4 = IsFinite<[arg1: string, ...args: string[]]> // false

 type Foo5 = IsFinite<[string, ...[string, number], ...string[], string]> // never <- doesn't handle this case

Try it out

Answer №1

When referring to an "infinite" array/tuple, it denotes an array type with no specified maximum length in TypeScript. In this case, the length property of the array type would be of type number, as opposed to a "finite" array/tuple where the length property is a numeric literal type or union of such literals:

type Length<T extends any[]> = T['length'];

type L1 = Length<[string]>                          // 1
type L2 = Length<[]>                                // 0
type L3 = Length<string[]>                          // number
type L4 = Length<[arg1: string, ...args: string[]]> // number
type L5 = Length<[string, ...[string, number], ...string[], string]> // number
type L6 = Length<[string, string?]> //  1 | 2

To define IsFinite<T>, you can use a conditional type that checks the type of the length property:

type IsFinite<T extends any[], F = true, I = false> =
    number extends T['length'] ? I : F

type Foo1 = IsFinite<[string]>                          // true
type Foo2 = IsFinite<[]>                                // true
type Foo3 = IsFinite<string[]>                          // false
type Foo4 = IsFinite<[arg1: string, ...args: string[]]> // false
type Foo5 = IsFinite<[string, ...[string, number], ...string[], string]> // false
type Foo6 = IsFinite<[string, string?]> //  true

Link to Playground for code testing

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

Angular Toaster Notification - There are currently no toaster containers set up to display notifications

Currently, I am utilizing the angular2-toaster library within my Angular application. It is quite straightforward - you simply define a toaster container in the template of your component: <toaster-container></toaster-container> Then, you ca ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Implementing Angular 2 reactive forms checkbox validation in an Ionic application

I have implemented Angular Forms to create a basic form with fields for email, password, and a checkbox for Terms&Conditions in my Ionic application. Here is the HTML code: <form [formGroup]="registerForm" (ngSubmit)="register()" class="center"> ...

Issue with Angular reactive forms when assigning values to the form inputs, causing type mismatch

I'm a beginner when it comes to reactive forms. I'm currently working on assigning form values (which are all string inputs) from my reactive form to a variable that is an object of strings. However, I am encountering the following error: "Type ...

Is it possible to access the attributes of an interface in TypeScript without relying on external libraries?

Ensuring the properties of an interface align with an object that implements it is crucial for successful unit testing. If modifications are made to the interface, the unit test should fail if it is not updated with the new members. Although I attempted ...

TypeScript 1.6 warning: Component XXX cannot be instantiated or called as a JSX element

var CommentList = React.createClass({ render: function () { return ( <div className="commentList"> Hello there! I am the CommentList component. </div> ); } }); var ...

How can I organize an array in JavaScript by date for presentation on a webpage?

Check out this code snippet: list.component.ts const data1 = [ { dateStart: "2020-02-14 00:00:01", name: 'Server1' }, { dateStart: "2020-02-13 14:00:01", name: 'Server1' }, ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Is there a way to dynamically adjust the size of mat dialog content to match the size of the mat dialog in

I have adjusted the size of my mat dialog, but the content is still stuck at the original size. To illustrate, here are some images: https://i.stack.imgur.com/2lLV2.jpg After researching, I found that it can be resized using CSS. I attempted the followin ...

Is there a way to set the submitted variable to true when the form group is submitted, then revert it to false when the user makes changes to the form?

With just one FormGroup, I ensure that when a user submits the form with errors the 'submitted' variable is set to true, displaying the errors. However, my challenge now is how to reset this variable to false when the user makes any changes after ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...

What could be the rationale behind the optional chaining operator not being fully compatible with a union of classes in TypeScript?

Imagine I have a combination of classes: type X = ClassA | ClassB | ClassC; Both ClassA and ClassC have a shared method called methodY. Why is it that I can't simply use the optional chaining operator to call for methodY? class ClassA { methodY ...