2

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?

1
  • Why are you trying to reassign a type? Do you mean let a: A = ['a', 'b'] or something? Commented Aug 7, 2022 at 22:43

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.