Search code examples
typescripttypescript-types

Typing a tuple of N numbers followed by a single string


Consider an array type like the following:

let example1: MyArray = ['John'],
    example2: MyArray = [4, 5, 1, 5, 'Eric'],
    example3: MyArray = [1, 5, 7, 3, 4, 5, 1, 'Joe'],
    ...

So one string in the end and an arbitrary count of numbers.

So far I can imagine a naive implementation of the MyArray type (which looks like the Death by a Thousand Overloads problem):

type MyArray = [string]
             | [number, string]
             | [number, number, string]
             | [number, number, number, string]
             | [number, number, number, number, string]
             ...

This is obviously suboptimal. Do better approaches exist?


Solution

  • Yes, you can type this, though only in Typescript 4.2 or later: Leading/Middle Rest Elements in Tuple Types.

    type MyArray = [...number[], string];
    
    const example1: MyArray = ['John'],
          example2: MyArray = [4, 5, 1, 5, 'Eric'],
          example3: MyArray = [1, 5, 7, 3, 4, 5, 1, 'Joe'];
    

    Prior to that, 3.0 introduced Rest elements in tuple types, but at that time, rest elements were limited to the end of the tuple. So you could do [string, ...number[]], but not [...number[], string].