DEV Community

Cover image for Typescript - (ReadOnly)NotEmptyArray
Luca Del Puppo for This is Learning

Posted on

 

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[]];
Enter fullscreen mode Exit fullscreen mode

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];
Enter fullscreen mode Exit fullscreen mode

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>>;
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

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

Bye Bye Guys 👋

Top comments (2)

Collapse
 
dcarapic profile image
Dalibor Čarapić

That is cool. Thank you for sharing.

Collapse
 
puppo profile image
Luca Del Puppo

I’m happy you enjoy it 😃

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post