Question
In TypeScript, what is the correct way to check whether a value is either null or undefined?
Because TypeScript is strongly typed, using a loose conditional such as if (value) {} does not seem precise enough when the goal is specifically to detect null and undefined.
Is there a dedicated TypeScript feature, built-in function, or syntax shortcut for checking both cases safely and clearly?
Short Answer
By the end of this page, you will understand how to check for null and undefined in TypeScript, when to use value == null, when to use strict comparisons, and why if (value) is often the wrong tool for this job. You will also see how these checks affect type narrowing in real code.
Concept
In TypeScript, null and undefined are two distinct values.
undefinedusually means a value was not provided or has not been assigned.nullusually means a value was intentionally set to “no value”.
Even though they are different, developers often need to treat them the same way: “this value is missing”.
That is why checks for both null and undefined are very common.
Why if (value) is not enough
A truthy check like this:
if (value) {
// ...
}
does not only exclude null and undefined. It also excludes other falsy values such as:
0""falseNaN
So if 0 or an empty string are valid values in your program, can give the wrong result.
Mental Model
Think of a variable as a mailbox.
undefinedmeans the mailbox was never given a letter.nullmeans someone deliberately placed a note saying, “there is no letter.”
In both cases, you still do not have a real message to read.
A check like value == null is like asking:
“Is the mailbox effectively empty, whether nothing was ever delivered or it was explicitly marked empty?”
A truthy check like if (value) asks a different question:
“Does this value look usable in a general boolean sense?”
That second question is broader, so it may reject values that are perfectly valid, such as 0 or "".
Syntax and Examples
Core syntax
Check for both null and undefined
if (value == null) {
// value is null or undefined
}
if (value != null) {
// value is neither null nor undefined
}
Explicit strict comparison
if (value === null || value === undefined) {
// missing value
}
if (value !== null && value !== undefined) {
// present value
}
Example 1: Safe string handling
function greet(name: string | null | undefined) {
if (name == null) {
console.();
;
}
.();
}
Step by Step Execution
Consider this example:
function printMessage(message: string | null | undefined) {
if (message != null) {
console.log(message.toUpperCase());
} else {
console.log("No message");
}
}
printMessage("hello");
printMessage(null);
printMessage(undefined);
Step by step
Call 1: printMessage("hello")
messagereceives the string"hello"- The condition
message != nullis checked "hello"is neithernullnorundefined- The condition is
true
Real World Use Cases
Where this is used
Form input handling
A field may be missing, intentionally blank, or contain a real value.
function validateAge(age: number | null | undefined) {
if (age == null) {
return "Age is required";
}
return age >= 18 ? "Adult" : "Minor";
}
API responses
External APIs often return optional or nullable properties.
type Product = {
price?: number | null;
};
function formatPrice(product: Product) {
if (product.price == null) {
return "Price unavailable";
}
return `$${product.price.toFixed(2)}`;
}
Configuration values
Real Codebase Usage
In real projects, developers usually combine null/undefined checks with a few common patterns.
Guard clauses
A guard clause exits early when required data is missing.
function sendEmail(address: string | null | undefined) {
if (address == null) {
throw new Error("Email address is required");
}
console.log(`Sending email to ${address}`);
}
This keeps the rest of the function simpler.
Default values
If a value is missing, provide a fallback.
function getDisplayName(name: string | null | undefined) {
return name ?? "Anonymous";
}
The ?? operator only falls back for null and undefined, not for or .
Common Mistakes
1. Using if (value) when 0, false, or "" are valid
Broken example:
function showPrice(price: number | null | undefined) {
if (price) {
console.log(price);
} else {
console.log("Missing price");
}
}
If price is 0, this incorrectly says it is missing.
Use this instead:
if (price != null) {
console.log(price);
}
2. Forgetting that null and undefined are different values
Broken example:
Comparisons
| Approach | Checks for null | Checks for undefined | Rejects 0/""/false | Best use |
|---|---|---|---|---|
if (value) | Yes indirectly | Yes indirectly | Yes | General truthy/falsy logic |
value == null | Yes | Yes | No | Check for missing value |
value != null | Excludes null | Excludes undefined |
Cheat Sheet
Quick reference
Check for missing value
value == null
True when value is:
nullundefined
Check for present value
value != null
True when value is not:
nullundefined
Explicit strict version
value === null || value === undefined
value !== null && value !== undefined
Use a default only for nullish values
const result = value ?? fallback;
Avoid this when valid values can be falsy
(value) {
}
FAQ
Is value == null valid in TypeScript?
Yes. It is a common and intentional way to check whether a value is either null or undefined.
Should I use if (value) to check for null and undefined?
Usually no. It also treats 0, false, "", and NaN as false, which may not match your intent.
What is the difference between null and undefined in TypeScript?
undefined usually means a value was not assigned or provided. null usually means the absence of a value was intentional.
Is == null better than === null || === undefined?
They are both correct. == null is shorter, while the strict version is more explicit.
Does TypeScript narrow types after value != null?
Yes. In many cases, TypeScript understands that the value is no longer or inside that branch.
Mini Project
Description
Build a small TypeScript utility for displaying profile information where some fields may be missing. This project demonstrates how to correctly check for null and undefined without accidentally rejecting valid values like 0 or an empty string.
Goal
Create a function that safely formats user profile data and provides sensible fallbacks only when values are actually missing.
Requirements
- Define a
UserProfiletype with nullable or optional fields. - Create a function that prints a user's name, age, and bio.
- Treat
nullandundefinedas missing values. - Do not treat
0as missing for age. - Use
??or!= nullwhere appropriate.
Keep learning
Related questions
Angular formGroup Error Explained: Fixing 'Can't bind to formGroup' in Reactive Forms
Learn why Angular shows 'Can't bind to formGroup' and how to fix it by importing ReactiveFormsModule correctly.
Fix "Element implicitly has an 'any' type" in TypeScript Object Indexing
Learn why TypeScript rejects string object indexing and how to fix it with keyof, unions, and typed object keys in React.
Fix "Property has no initializer" in Angular TypeScript Components
Learn why Angular TypeScript shows "Property has no initializer" and how to fix it using defaults, optional properties, or definite assignment.