Non-null assertion (!)

An exclamation mark after an expression removes null and undefined from the type without checking.

On this page

Example

#
TypeScript
const lessons = new Map<string, number>([['html', 11], ['css', 9]])

const htmlModules = lessons.get('html')!
console.log(htmlModules + 1)

const pythonModules = lessons.get('python') ?? 0
console.log(pythonModules)
Result
12
0

Definition and usage

#

The ! operator placed after an expression tells the compiler: “this value is definitely not null or undefined”. The type HTMLElement | null becomes HTMLElement.

Like the as assertion, it checks nothing at runtime. If the value turns out to be null after all, you get a runtime error, exactly the kind strictNullChecks protects you from.

Use it only when you’re sure from another source, for example the element exists in the page template. In other cases it’s better to handle the missing value with a condition or with the ?. and ?? operators.

Syntax

#
Syntax
expression!

More examples

#
An exclamation mark where there is no value
TypeScript
const missing = lessons.get('rust')!
try {
  console.log(missing.toFixed(0))
} catch (error) {
  console.log('Runtime error: the value was undefined')
}
Result
Runtime error: the value was undefined

Good practices

#
  • Every ! in your code is a place where you switch off the compiler’s protection. Consider whether it’s better to handle the missing value.
  • In tests and quick scripts, ! is sometimes acceptable. In production code, prefer explicit checks.

Related entries

#

Spotted a mistake or missing an example? Write to us.