When a value can be null, TypeScript won’t let you use it as text or a number until you check it. After a check such as if (!text) return …;, TypeScript knows that text isn’t null below it. This is called narrowing.
Every command and output on this page is real, run with Node.js 26.13.1 and TypeScript 7.0.2 on macOS.
Syntax
function name(value: Type | null) {
if (!value) {
return fallback;
}
// below the check, value is a Type
}
Type | null: the value is either aTypeornull.if (!value): catchesnulland leaves the function early.- Below the check, TypeScript treats
valueas a plainType.
See Narrowing (opens in a new tab) in the TypeScript handbook, under Truthiness narrowing.
Prerequisites
- Node.js 24.12 or later, which runs TypeScript files directly. Install it from the Node.js download page (opens in a new tab).
- TypeScript, for the
tsccommand. Install it withnpm install -g typescript, as the TypeScript download page (opens in a new tab) shows.
The Example
A shout function that turns text into capitals, but may be given null instead of text. The file is shout.ts.
Step 1: Write the Code
function shout(text: string | null) {
return text.toUpperCase();
}
console.log(shout("hello"));
Step 2: Check It with tsc
tsc --noEmit shout.ts
shout.ts(2,10): error TS18047: 'text' is possibly 'null'.
text can be null, and null has no toUpperCase(), so tsc stops at line 2.
Step 3: Fix It
Check text first, and leave the function when it’s missing:
function shout(text: string | null) {
if (!text) {
return "Nothing to say";
}
return text.toUpperCase();
}
console.log(shout("hello"));
console.log(shout(null));
Step 4: Check It and Run It
Check it again. No output means tsc found no errors:
tsc --noEmit shout.ts
Then run it:
node shout.ts
HELLO
Nothing to say
Below the check, TypeScript knows text is a string. The call with null took the early return.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Silencing the error with text! | tsc is quiet, but null still crashes at run time: TypeError: Cannot read properties of null (reading 'toUpperCase') | Check the value with if |
Checking with !text when empty text is a valid value | Empty text is caught by the check too | Check text === null instead |
FAQ
Which checks narrow a type?
Truthiness checks like this one, typeof, ===, instanceof and in, among others. The TypeScript handbook’s Narrowing page goes through them.
Conclusion
Check a value that can be null before you use it. Below the check, TypeScript narrows its type, and the possibly null error is gone.
Additional Resources
- Narrowing (opens in a new tab) (TypeScript handbook)
- Everyday Types (opens in a new tab): union types and null (TypeScript handbook)
TypeScript, Node.js and other names mentioned are trademarks of their respective owners.
0 comments