Typescript - Tips & Tricks - Non-null assertion operator

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.
In this series, You'll see some tips and tricks using Typescript
Today I want to talk about the never type. As you can understand, this type identifies a piece of code that will never be executed or represents a state that shouldn’t exist. Here an example const throwException: () => never = () => { throw new E...
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...

In some cases, you have a field that you initialize in a method, and if you follow the flow of the code you are sure that this field is initialized but typescript doesn't understand it. An example
type Person = {
name: string;
};
let person: Person;
function initialize() {
person = { name: "name" };
}
initialize();
console.log("Hello", person.name); // Variable 'person' is used before being assigned.
In this case, you can see how the typescript compiler doesn't understand that the "person" field isn't null but it's initialized. To resolve this problem, the typescript language exposes us the "Non-null assertion operation"(!). This operator says to the compiler that the field isn't null or undefined but it's defined. The previous example can be reviewed in this way
type Person = {
name: string;
};
let person: Person;
function initialize() {
person = { name: "name" };
}
initialize();
console.log("Hello", person!.name);
As you can see, in this case, the code doesn't have errors and the compilation ends with success.
That's all for today! Bye-bye guys!