Logo

How to declare a type as nullable in TypeScript?

To make a type nullable in TypeScript, union it with null (and/or undefined if desired). For example:

type MaybeString = string | null;

Now, MaybeString can hold either a string or null. If you want to account for undefined too, do:

type MaybeString = string | null | undefined;

Details

  1. Union with null

    let value: string | null = null; value = "Hello"; // also valid
  2. Union with undefined
    If you want to allow the variable to be undefined, add it to the union:

    let anotherValue: string | null | undefined; anotherValue = "World!"; anotherValue = undefined;
  3. Optional Properties
    If you’re marking properties as optional in interfaces or type definitions, you can use the ? syntax, which implicitly makes them type | undefined:

    interface Person { name: string; nickname?: string; // string | undefined }
  4. Strict Null Checks

    • In tsconfig.json, strictNullChecks should be true to distinguish between null and undefined.
    • With strict null checks enabled, you can’t assign null or undefined to a non-nullable type.

If you want to strengthen your JavaScript knowledge (which underpins TypeScript), consider Grokking JavaScript Fundamentals by DesignGurus.io. It covers core topics like prototypes, closures, and async patterns—helping you better understand TypeScript’s typing of null/undefined and other advanced features.

CONTRIBUTOR
TechGrind