Non-null Assertion Operator

You can use the “non-null assertion operator” to tell the compiler that you’re certain that an expression won’t be null or undefined. This operator is represented by an exclamation mark (!) placed after the expression.

In the code snippet below, name! tells the TypeScript compiler to assume that the name property is not null or undefined. This allows to access the length property without the compiler raising an error:

1
2
3
function getNameLength(user: { name?: string }): number {
return user.name!.length;
}