Learn TypeScript

Using the non-null assertion operator

Using the non-null assertion operator

In this lesson, we will learn how the non-null assertion operator can narrow a type.

Understanding use cases for the non-null assertion operator

We are going to explore the non-null assertion operator in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The code contains a function that has a type error in its return statement.

🤔

Step through the code in your head. Will the text variable ever be null on the return statement?

So, this is a case where we know more about the code than TypeScript does. We can, of course, use a type assertion to resolve the type error. However, the non-null assertion operator is a more concise solution to type errors that involve null or undefined.

It is worth noting that if the code were more straightforward, then TypeScript would understand that text on the return statement wasn't null.

function duplicate(text: string | null) {
if (text === null || text === undefined) {
text = "";
}
return text.concat(text);
}

Our code is running in strict mode with strictNullChecks on. If strictNullChecks is off, then the non-null assertion operator isn't required. We will learn about strict mode and strictNullChecks later in this course.

Non-null assertion operator syntax

The non-null assertion operator is an exclamation mark (!), and this is placed after the variable or expression that we want to tell TypeScript isn't null or undefined.

An example

  • Update the return statement in code with the non-null assertion operator to resolve the type error.

Nice!

Summary

The non-null assertion operator is a concise way of avoiding unnecessary null and undefined checks in our code. We should only use this when we definitely know the variable or expression can't be null or undefined.

Did you find this lesson useful?

Share this lesson on twitter
© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more