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 100,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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.