
Matthew C.
—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.
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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “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.
