TypeScriptUnions and narrowing
Non-null assertion (!)
An exclamation mark after an expression removes null and undefined from the type without checking.
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
#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
#- null and undefinedThe types for the absence of a value, controlled by strictNullChecks.
- Type assertion (as)Telling the compiler the type of a value when you know more than it does.
- Type narrowingDetermining a more precise type for a value based on checks in your code.
- "strictNullChecks"Treats null and undefined as separate types, forcing you to handle them.
Spotted a mistake or missing an example? Write to us.