Nullable types make missing values explicit so code can handle them before use.

nullable value A nullable type such as `string | null` says the value might be present or intentionally empty.

Null and Undefined

nickname
nullable.ts
Replay: real traced execution (multi-file project)
function labelName(name: string | null): string {
    if (name === null) {
        return "anonymous";
    }
    return name.toUpperCase();
}

const nickname: string | null = null;
const label: string = labelName(nickname);

console.log(`name=${label}`);
function labelName(name: string | null): string {
    if (name === null) {
        return "anonymous";
    }
    return name.toUpperCase();
}

const nickname: string | null = "Ada";
const label: string = labelName(nickname);

console.log(`name=${label}`);
function labelName(name: string | null): string {
    if (name === null) {
        return "anonymous";
    }
    return name.toUpperCase();
}

const nickname: string | null = "Milo";
const label: string = labelName(nickname);

console.log(`name=${label}`);
  1. nickname ← null

    5    return name.toUpperCase();6}78const nickname→ null: string | null = null;  //@nickname="Ada", "Milo"9const label: string = labelName(nicknamenull);
  2. function labelName(name: string | null): string

    1function labelName(namenull: string | null): string {2    if (name === null) {
  3. if (name === null)

    1function labelName(name: string | null): string {2    if (namenull === null) {3        return "anonymous";4    }
  4. label ← anonymous

    8const nickname: string | null = null;  //@nickname="Ada", "Milo"9const label→ anonymous: string = labelName(nicknamenull);1011console.log(`name=${labelanonymous}`);
    outputname=anonymous
  1. nickname ← Ada

    5    return name.toUpperCase();6}78const nickname→ Ada: string | null = "Ada";9const label: string = labelName(nicknameAda);
  2. function labelName(name: string | null): string

    1function labelName(nameAda: string | null): string {2    if (name === null) {3        return "anonymous";4    }5    return nameAda.toUpperCase();6}
  3. label ← ADA

    8const nickname: string | null = "Ada";9const label→ ADA: string = labelName(nicknameAda);1011console.log(`name=${labelADA}`);
    outputname=ADA
  1. nickname ← Milo

    5    return name.toUpperCase();6}78const nickname→ Milo: string | null = "Milo";9const label: string = labelName(nicknameMilo);
  2. function labelName(name: string | null): string

    1function labelName(nameMilo: string | null): string {2    if (name === null) {3        return "anonymous";4    }5    return nameMilo.toUpperCase();6}
  3. label ← MILO

    8const nickname: string | null = "Milo";9const label→ MILO: string = labelName(nicknameMilo);1011console.log(`name=${labelMILO}`);
    outputname=MILO