Typescript - (ReadOnly)NotEmptyArray

Full Stack Developer and JavaScript and TypeScript enthusiastic.
Search for a command to run...

Full Stack Developer and JavaScript and TypeScript enthusiastic.
No comments yet. Be the first to comment.
Today, I wanna show you how to set up your devices with Antigravity using only the agentic mode, without touching any code. At the last CodeMotion Rome, I got my special badge. A CM Node, a special ha

As a developer, you have to take control of your projects every day. Whether it is a company repository, an open source project you maintain or collaborate on, or a simple pet project. Gaining control over your projects often depends on the platform ...

My Antigravity first experience

Write clear and insightful commit messages using AI and GitLens.

We are in the AI era. New models emerge daily, and many applications have already integrated AI into their workflows. Gemini, OpenAI, Copilot, Deepseek, Llama, and many others enable AI in your applications or help you write code, but they all need a...

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.

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 https://gist.github.com/Puppo/bc5287d32dbfeeba9f14862654cece9d %}
That's all, I hope it can be helpful in your daily work.
Bye Bye Guys 👋