Non-null assertion operator: !
- You tells the TS compiler that the value of a variable is not
null | undefined
- Use it when you are in possession of knowledge that the TS compiler lacks.
Here is a trivial example of what it does:
let nullable1: null | number;
let nullable2: undefined | string;
let foo = nullable1! // type foo: number
let fooz = nullable2! // type fooz: string
It basically removes null | undefined
from the type
When do I use this?
Typescript is already pretty good at inferring types for example using typeguards:
let nullable: null | number | undefined;
if (nullable) {
const foo = nullable; // ts can infer that foo: number, since if statements checks this
}
However sometimes we are in a scenario which looks like the following:
type Nullable = null | number | undefined;
let nullable: Nullable;
validate(nullable);
// Here we say to ts compiler:
// I, the programmer have checked this and foo is not null or undefined
const foo = nullable!; // foo: number
function validate(arg: Nullable) {
// normally usually more complex validation logic
// but now for an example
if (!arg) {
throw Error('validation failed')
}
}
My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.