Non-null Assertion Operator
Use the ! operator to assert a value is not null or undefined.
The Non-Null Assertion Operator
The postfix ! operator tells TypeScript 'this value is not null or undefined here.' It removes those from the type without any runtime check.
function firstChar(s: string | null): string {
return s!.charAt(0); // assert s is not null
}
console.log(firstChar('hello'));Where You Place the !
The ! goes immediately after the expression you're asserting, before any further access. It strips null | undefined from that expression's type.
type Box = { value?: number };
const box: Box = { value: 7 };
const n: number = box.value!; // value is number | undefined -> number
console.log(n);All lessons in this course
- The as Keyword for Type Assertions
- Non-null Assertion Operator
- Double Assertions and Their Risks
- Assertions vs Type Guards