Execute Program

TypeScript Basics: Nullability

Welcome to the Nullability lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • In JavaScript, any variable can be null or undefined. This is an endless source of bugs. Is this familiar? TypeError: Cannot read properties of undefined (reading 'someProperty')

  • TypeScript isn't perfect. It can't ensure that we never encounter these kinds of bugs. However, it can make them far less likely!

  • In TypeScript, the undefined value has a special type, undefined. No other value has the type undefined, not even null.

  • >
    let notDefined: undefined = undefined;
    notDefined;
    Result:
    undefinedPass Icon
  • >
    let notDefined: undefined = null;
    notDefined;
    Result:
    type error: Type 'null' is not assignable to type 'undefined'.Pass Icon
  • Types other than undefined can never have the value undefined. That's how TypeScript stops accidental undefined values from showing up.

  • >
    let aNumber: number = undefined;
    aNumber;
    Result:
    type error: Type 'undefined' is not assignable to type 'number'.Pass Icon
  • However, sometimes we want undefined values. In those cases, we can use a type union to explicitly allow undefined.

  • >
    let numberMaybe: number | undefined = 5;
    numberMaybe;
    Result:
    5Pass Icon
  • >
    let numberMaybe: number | undefined = undefined;
    numberMaybe;
    Result:
    undefinedPass Icon
  • >
    let possiblyBoolean: boolean | undefined = null;
    possiblyBoolean;
    Result:
    type error: Type 'null' is not assignable to type 'boolean | undefined'.Pass Icon
  • When we allow undefined in this way, it's still tightly controlled. For example, normally we can't assign a string | undefined to a string.

  • >
    let mightBeString: string | undefined = true ? 'a' : undefined;
    let s: string = mightBeString;
    s;
    Result:
    type error: Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.Pass Icon
  • But if we narrow the type to just string, we can make that assignment.

  • >
    let mightBeString: string | undefined = true ? 'a' : undefined;
    let s: string;
    if (mightBeString === undefined) {
    s = '';
    } else {
    s = mightBeString;
    }
    s;
    Result:
    'a'Pass Icon
  • One final note about TypeScript's --strictNullChecks option, which changes type checking for null and undefined. In this TypeScript course, --strictNullChecks is always enabled. If you try our example code in a TypeScript environment without that option enabled, you may see different results. We discuss TypeScript compiler options later in our TypeScript courses.