Sub topic 9
The non-null assertion (`!`) and its risks
Prerequisites: you should know basic TypeScript types, union types, type annotations, and JavaScript’s null and undefined. This chapter assumes strictNullChecks is enabled.
What the non-null assertion does
The non-null assertion operator is a postfix !. It tells TypeScript, “This expression is not null or undefined here.” TypeScript removes null and undefined` from the expression’s type, but it does not add a runtime check.
function printName(name: string | null): void {
console.log(name!.toUpperCase());
}
printName("Ada");Inside printName, name still could be null at runtime. If that happens, name!.toUpperCase() throws a TypeError. The exclamation mark changes only the compiler’s view of the value.
A safer version proves the value is present:
function printName(name: string | null): void {
if (name === null) {
return;
}
console.log(name.toUpperCase());
}The check narrows name from string | null to string. This makes the runtime behavior match the type.
When `!` can be justified
Use a non-null assertion only when the surrounding program guarantees a value that TypeScript cannot prove. For example, a function might run only after initialization:
interface Config {
apiUrl: string;
}
let config: Config | undefined;
function initialize(): void {
config = { apiUrl: "https://example.test" };
}
function requestUrl(): string {
return config!.apiUrl;
}
initialize();
console.log(requestUrl());This example works because initialize() runs before requestUrl(). However, the guarantee is not visible in the type of requestUrl. A later caller could use the function incorrectly.
A better design passes the initialized value as an argument:
interface Config {
apiUrl: string;
}
function requestUrl(config: Config): string {
return config.apiUrl;
}
const config: Config = { apiUrl: "https://example.test" };
console.log(requestUrl(config));The type now records the requirement. Callers cannot omit the configuration.
| Situation | Better choice |
|---|---|
| A local check proves presence | Narrow with `if` |
| A fallback is valid | Use `??` |
| A function requires a value | Pass a non-null parameter |
| An external lifecycle guarantees presence | Use `!` sparingly and document it |
| Presence is uncertain | Keep the nullable type |
Assertions at API boundaries
APIs often return nullable values. For example, querySelector returns Element | null, and Map.get returns T | undefined.
const settings = new Map<string, string>();
settings.set("theme", "dark");
const theme = settings.get("theme");
if (theme !== undefined) {
console.log(theme.toUpperCase());
}Using settings.get("theme")! might be reasonable if the key is controlled and its presence is guaranteed by an invariant. It is risky when the key comes from user input, a file, a network response, or a changing data source. At those boundaries, check the result or return an explicit error.
Definite assignment assertions
A related syntax is a ! after a class property name:
class App {
root!: HTMLElement;
mount(root: HTMLElement): void {
this.root = root;
}
show(): void {
this.root.hidden = false;
}
}
const app = new App();
app.mount(document.body);
app.show();root!: HTMLElement tells TypeScript that the property will be assigned before it is read. It suppresses strict property initialization checking. It does not initialize root.
Prefer constructor initialization when possible:
class Label {
constructor(public text: string) {}
}The constructor makes the object valid immediately. Use a definite assignment assertion only when a framework or controlled lifecycle performs the assignment and that lifecycle is reliable.
Exercise
Exercise
Why can user!.name still throw an exception, and what should you do when user presence is uncertain?
Show answer
The ! changes only TypeScript's compile-time type and does not check the value at runtime. Check user before reading name, or use a valid fallback with ??.