John
John

Reputation: 11399

Is it possible to create a type or interface which is an Array with exactly "n" entries in TypeScript?

I want to create an Array with maximum and minimum two entries. Here is an example of expected behaviour:

const foo1: IShortArray = ['bar', 'baz', 'foz']; // TypeScript: error
const foo2: IShortArray = ['bar']; // TypeScript: error
const foo3: IShortArray = ['bar', 'baz']; // TypeScript: OK

I have tried something like this:

export interface IShortArray extends Array<string> {
  0: string;
  1: string;
}

Which does compile, but it is not working as expected.

Upvotes: 1

Views: 45

Answers (1)

Gasoline and Sauce
Gasoline and Sauce

Reputation: 149

There's already a primitive type for that called a Tuple. A Tuple allows you to define an array with a known number of items and just like an Array, you can store different data types in it.

It would look something like this:

type IShortArray = [string, string]

const foo1: IShortArray = ['bar', 'baz', 'foz']; // TS: error
const foo2: IShortArray = ['bar']; // TS: error
const foo3: IShortArray = ['bar', 'baz']; // TS: OK

Here's the link to the docs for further reading.

Upvotes: 3

Related Questions