Typescript - (ReadOnly)NotEmptyArray

February 14, 2022

282 words

Post contents

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.

export interface NonEmptyArray<A> extends ReadonlyArray<A> {  // tslint:disable-next-line: readonly-keyword  0: A;}type ReadOnlyNotEmptyArray<T> = Readonly<NotEmptyArray<T>>;function isNotEmptyArray<T>(as: T[]): as is NotEmptyArray<T> {  return as.length > 0;}function freeze(as: NotEmptyArray<T>): ReadOnlyNotEmptyArray<T> {  return Object.freeze(as);}const head = <T>(as: NotEmptyArray<T>): T => as[0];const tail = <T>([, ...rest]: NotEmptyArray<T>): T[] => rest;

Puppo / NotEmptyArray.ts

View Gist

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

Bye Bye Guys 👋

Subscribe to our newsletter!

Subscribe to our newsletter to get updates on new content we create, events we have coming up, and more! We'll make sure not to spam you and provide good insights to the content we have.