Typescript - (ReadOnly)NotEmptyArray

ยท

2 min read

Typescript - (ReadOnly)NotEmptyArray

Arrays are already well described in typescript, but sometimes we need to be more strict with our types. For instance, we need to have a not empty array. This type doesn't exist in the typescript definitions, but we can create it in this way.

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

This type inherits all the characteristics of the array type and it adds another rule to it. This array must have at least one item. It can be used thus

const array: NotEmptyArray<number> = [1];

If you try to use it without any elements, typescript gives you an error, and it says us that a NotEmptyArray must have at least one element.

NotEmptyArray

But this type could create some problems. If you use the arrays' methods that remove elements, you could have errors, because the arrays could become empty. To avoid this issue, we can work with read-only arrays that can be defined thus.

type ReadOnlyNotEmptyArray<T> = Readonly<NotEmptyArray<T>>;

This type prevents all the arrays' mutations so we can work with arrays with confidence.

The last point that I want to let you is how to convert an Array to a NotEmptyArray. To do that we need to create a type guard function. This function can be done in this way.

function isNotEmptyArray<T>(as: T[]): as is NotEmptyArray<T> {
  return as.length > 0;
}

Therefore you can check if an array has at least an element and if it respects this rule it's a NotEmptyArray.

I created a GitHub Gist with this code if you need it.

{% gist gist.github.com/Puppo/bc5287d32dbfeeba9f148.. %}

That's all, I hope it can be helpful in your daily work.

Bye Bye Guys ๐Ÿ‘‹

ย