Skip to content

Latest commit

 

History

History
35 lines (24 loc) · 1.08 KB

create-a-non-empty-array-type.md

File metadata and controls

35 lines (24 loc) · 1.08 KB

Create A Non-Empty Array Type

An array type (e.g. Array<string>) by default will allow an empty array. We can define a custom array type that does static type checking to ensure arrays aren't declared as empty.

To do this, we specify the array type has at least one item in addition to the spread of the rest of the array.

type NonEmptyArray<T> = [T, ...T[]];

If we declare a NonEmptyArray with no items:

const statuses: NonEmptyArray<string> = [];

We'll get the following type error:

Type '[]' is not assignable to type 'NonEmptyArray<string>'.
  Source has 0 element(s) but target requires 1.

Whereas as soon as we add at least one item, the type error goes away.

const statuses: NonEmptyArray<string> = ['active'];

Here is a TS Playground example of this type.

source