Home > Back-end >  How to define an array type in TypeScript which enforces more than one element of a given type?
How to define an array type in TypeScript which enforces more than one element of a given type?

Time:08-08

I can create a type for an array of N element of string type:

type A = string[];

as well as a predefined number of elements, such as exactly 2 elements:

type A = [string, string];

What I am trying to have is a type that will accept 2 or more elements, but not just one or none.

type A = ?

A = ['a', 'b'];  // OK 
A = ['a', 'b', 'c'];  // OK 
A = ['a', 'b', ... 'N'];  // OK 
A = ['a'];  // Error
A = [];  // Error

Is this possible?

CodePudding user response:

You can use rest elements in tuple types to indicate that the tuple type is open-ended and may have zero or more additional elements of the array element type:

type A = [string, string, ...string[]];

The type A must start with two string elements and then it can have any number of string elements after that:

let a: A;
a = ['a', 'b'];  // OK 
a = ['a', 'b', 'c'];  // OK 
a = ['a', 'b', 'c', 'd', 'e', 'N'];  // OK 
a = ['a'];  // error! Source has 1 element(s) but target requires 2
a = [];  // error!  Source has 0 element(s) but target requires 2.

Playground link to code

  • Related