null and undefined
Represent missing or empty values, and understand strict null checking.
Syntax
let x: string | null = null;TypeScript has two types for absent values:
undefined— a variable that has not been given a value.null— an intentional "no value".
With strict mode on, you cannot assign null or undefined to a normal typed variable unless you allow it in the type (for example with a union like string | null).
Example
Loading editor…
Press Run to execute the code.
When to use it
- A user lookup function returns string | null so callers must handle the case where the user is not found.
- Strict null checks prevent a developer from calling methods on a potentially undefined configuration value.
- An optional field in a form interface is typed as string | undefined, requiring a presence check before use.
More examples
Nullable return type
Returns null when a user is not found and guards the call site, a classic strict-null pattern.
function findUser(id: number): string | null {
const users: Record<number, string> = { 1: 'Alice', 2: 'Bob' };
return users[id] ?? null;
}
const name = findUser(3); // name is string | null
if (name !== null) {
console.log(name.toUpperCase());
}Optional property is undefined
Uses an optional property (implicitly number | undefined) and the nullish coalescing operator to provide a default.
interface Config {
host: string;
port?: number; // number | undefined
}
function connect(cfg: Config): void {
const port = cfg.port ?? 3000; // default if undefined
console.log(`${cfg.host}:${port}`);
}Strict null check enabled
Enabling strictNullChecks (included in strict: true) forces all potential null/undefined values to be explicitly handled.
{
"compilerOptions": {
"strictNullChecks": true
}
}
Discussion