How to fix the forbidden non-null assertion in TypeScript and React?

Matthew C.
—The Problem
When using typescript-eslint in a JavaScript application, you may encounter the following error:
@typescript-eslint/no-non-null-assertion warning: Forbidden non-null assertion
The following example code would cause this error:
const loggedInUsername = "bob"; const users = [ { name: "Steven", age: 12 }, { name: "Lisa", age: 32 } ]; const loggedInUser = users.find((u) => u.name === loggedInUsername); console.log(loggedInUser!.age);
You can see a live demo of this error in this typescript-eslint playground.
For this error to occur, the eslintrc file has the “no-non-null-assertion” rule set to "error":
"rules": { "@typescript-eslint/no-non-null-assertion": "error" }
The Non-null Assertion Operator (Postfix !) assertion removes the null and undefined types from a value. To use it, add the ! symbol after an expression like in the console log example above. When your TypeScript configuration is set to do "strictNullChecks", use the non-null assertion operator to bypass the null and undefined type checks. It should only be used if you know a specific value won’t be null or undefined at runtime.
The Solution
Your error message may include a solution to the error:
Consider using the optional chain operator `?.` instead. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator.
To fix the example code above, use the optional chain operator when accessing the age property of the loggedInUser:
console.log(loggedInUser?.age);
If the age property does not exist on the loggedInUser object, the expression will result in undefined instead of throwing an error.
- Sentry BlogGuide to Error & Exception Handling in React
- Sentry BlogHow to identify fetch waterfalls in React
- Syntax.fmReact Server Components
- Sentry BlogSentry can’t fix React hydration errors, but it can really help you debug them
- Syntax.fmWhy the jQuery Creator Uses React and Typescript
- Syntax.fmListen to the Syntax Podcast
- Sentry BlogReact Native Debugging and Error Tracking During App Development
- Syntax.fmDiscussion on building native iOS and Android apps with React Native
- SentryReact Error & Performance Monitoring
- Sentry BlogFixing memoization-breaking re-renders in React
- SentryReact Debug Hub
- Listen to the Syntax Podcast
![Syntax.fm logo]()
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODES
Considered “not bad” by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
