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

Utilizing TypeScript to perform typing operations on subsets of unions

A TypeScript library is being developed by me for algebraic data types (or other names they may go by), and I am facing challenges with the more complex typing aspects. The functionality of the algebraic data types is as follows: // Creating ADT instatiat ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

The 'required' validator in Mongoose seems to be malfunctioning

I've been attempting to validate the request body against a Mongoose model that has 'required' validators, but I haven't been successful in achieving the desired outcome so far. My setup involves using Next.js API routes connected to Mo ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

Add the specified HTML tag to the existing document. An error has occurred: HierarchyRequestError - The action would result in an invalid node

During my testing of a React/TypeScript project using Jest + Enzyme, I encountered an issue when trying to append an HTML tag. The error occurred with the following unit test code: const htmlTag: HTMLElement = document.createElement('html'); htm ...

Import statements cannot be used outside of a module when working with a private npm package in cucumber.js

Utilizing cucumberjs to test various components of my project has been successful. However, I encountered an issue in one step where I utilize a zod schema that is defined within a private npm module: // within the private npm package: // constant.js impor ...

Sending the value of "username" between two components within Angular 2

I have a good understanding of nesting child components within parent components in Angular 2, but I'm a bit unclear on how to pass a single value from one component to another. In my scenario, I need to pass a username from a login component to a cha ...

Tips on sending various properties to makeStyles() using TypeScript

After learning how to pass 1 prop to makeStyle() from a resource, I decided to try passing in 2 props for my project. However, I encountered an error stating cannot find name 'props'. Any assistance on this issue would be greatly appreciated! con ...

Challenges with passing props to a higher order stateless component in React using Typescript

I'm having trouble creating a NavLink following the react-router tutorial. I'm not sure why it's not working with Typescript 2.1 import React from 'react'; import { Link, LinkProps } from 'react-router'; const NavLink: ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

Guide to implementing Apollo GraphQL subscriptions in NextJS on the client-side

As a newcomer to NextJS, I am facing the challenge of displaying real-time data fetched from a Hasura GraphQL backend on a page. In previous non-NextJS applications, I successfully utilized GraphQL subscriptions with the Apollo client library which levera ...

Utilizing two DTOs for a single controller in NestJS

I'm having trouble retrieving and transforming different types of dtos from the body. My goal is to extract and transform firstDto if it's incoming, or convert secondDto if that's what's being received. However, my current code isn&apos ...

Unable to access the redux store directly outside of the component

When trying to access my store from a classic function outside the component, I encountered an error while calling getState(): Property 'getState' does not exist on type '(initialState: any) => any' Below is the declaration and im ...

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Decide on the return type of a generic function depending on the parameters of the function

I have a series of TypeScript functions that are structured as follows: useCustomFunction = <T>(key: CustomType) : T => { // implementation details here } The parameter type is restricted to a specific set of strings: type CustomType = "apple ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

Differences between JSX.Element, ReactNode, and ReactElement: When should each be utilized?

Currently in the process of transitioning a React application to TypeScript. Everything seems to be going smoothly, however I've encountered an issue with the return types of my render functions, specifically within my functional components. In the p ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...