Non-null assertion
- TypeScript course
- Advanced
- Lesson 47/57
- 4 min
Learn non-null assertion with the ! operator.
Non-null assertion
The ! operator after an expression makes a non-null assertion: it tells TypeScript "this value is not null or undefined". If the value is string | null, the expression v! is narrowed to string. But no real check is performed at runtime; if the value is null, an error still occurs.
function upper(v: string | null): string {
return v!.toUpperCase(); // assertion: v is string
}Assertion vs check
The difference between non-null assertion ! and a real null check if (v !== null) is whether checks are performed. With if, a real check is done and is safe; with !, only the compiler is trusted, and a runtime error may occur. ! should only be used when you're sure the value isn't null.
// Safe: real check
function safe(v: string | null): string {
if (v !== null) return v.toUpperCase();
return "";
}
// Risky: assertion
function risky(v: string | null): string {
return v!.toUpperCase(); // runtime error if v is null
}Practice Handle nullable with non-null assertion
Write an upper(v: string | null): string function. Return the expression v!.toUpperCase() (using non-null assertion). Print the result via console.log(upper("hello")).
Starter code
// upper fonksiyonunu nullable string parametreyle yaz
// non-null assertion ile toUpperCase ifadesini döndür
// upper("hello") sonucunu yazdırSample solution
function upper(v: string | null): string {
return v!.toUpperCase();
}
console.log(upper("hello"));Expected output
HELLO
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the v! expression do?
- It makes v null
- It narrows v to non-null type (no runtime check) Correct answer
- It makes v undefined
- It performs a null check at runtime
Explanation: The v! expression asserts to TypeScript that v is not null; it narrows at compile time but performs no runtime check, so an error still occurs if it is null.
2 Non-null assertion
function upper(v: string | null): string {
return ____;
}
function upper(v: string | null): string {
return v!.toUpperCase();
}
Explanation: The v!.toUpperCase() expression asserts that v is not null and allows the toUpperCase call; there is no runtime check.
3 Non-null assertion parts
| Term | Meaning |
|---|---|
v! |
non-null assertion |
if (v !== null) |
real check |
çalışma zamanı |
no check |
! operatörü |
after expression |