3 min read
•Question 25 of 48easyWhat is the Non-null Assertion Operator?
Asserting values are not null.
What You'll Learn
- Non-null assertion (!)
- When to use it
- Risks and alternatives
Non-null Assertion (!)
Tells TypeScript a value is not null or undefined.
code.tsTypeScript
function getValue(): string | null {
return "hello";
}
// TypeScript thinks value might be null
const value = getValue();
console.log(value.length); // Error!
// Assert it's not null
console.log(value!.length); // OKCommon Use Cases
code.tsTypeScript
// DOM elements you know exist
const button = document.getElementById("submit")!;
button.addEventListener("click", handleClick);
// After null checks
function process(value: string | null) {
if (!value) return;
// TypeScript already knows value is string here
// but in some cases you might need:
const upper = value!.toUpperCase();
}Risks
code.tsTypeScript
const element = document.getElementById("nonexistent")!;
element.click(); // Runtime error!Safer Alternatives
code.tsTypeScript
// Type guard
if (value !== null) {
console.log(value.length);
}
// Optional chaining
console.log(value?.length);
// Nullish coalescing
const safeValue = value ?? "default";