🧠🇹 When to use the non-null assertion operator in TypeScript
Audrey Kadjar
Posted on July 17, 2024
Did you know that TypeScript has a non-null assertion operator?
The non-null assertion operator (!) is used to assert that a value is neither null nor undefined. It tells TypeScript's type checker to ignore the possibility that the value is null or undefined, thus bypassing type checking for these values.
When to use it
Use the non-null assertion operator when you are certain that a variable will be assigned a non-null value when you access it (for example, after a type guard).
In the example below, we use a non-null assertion operator (at user.email!
) because we're certain that the value of the email property exists. Even though email is defined as an optional value in the User interface, we're checking for its existence with a type guard in the getEmail function, so we can be sure that it exists.
Feel free to check this example in the TypeScript Playground and play with it.
interface User {
id: number;
name: string;
email?: string;
}
function getEmail(user: User): string {
if (!user.email) return 'N/A';
return user.email!;
}
const user: User = { id: 1, name: 'Alice', email: "alice@email.com"};
const email = getEmail(user);
console.log(`User's email: ${email}`);
Notice in this example that TypeScript would not throw an error if we removed the non-null assertion operator.
In TypeScript, while accessing optional properties like email without the non-null assertion operator is allowed, adding the non-null assertion operator can assert your understanding that the property is indeed present when accessed. This can be helpful for clarity and documentation, especially in large codebases or when working in teams. It also prevents TypeScript from warning you about potentially undefined values and allows you to treat the property as if it is always present, avoiding unnecessary runtime checks.
Hope this article has clarified the use of the intriguing non-null assertion operator in TypeScript!
Feel free to reach out if you have any questions! You can also find me on Github, LinkedIn, and Instagram.
Posted on July 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.