Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define an array type in TypeScript which enforces more than one element of a given type?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type A = ?

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

Is this possible?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading