null and undefined

Represent missing or empty values, and understand strict null checking.

Syntaxlet 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

Try it yourself
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.

Example · ts
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.

Example · ts
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.

Example · json
{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

Discussion

  • Be the first to comment on this lesson.