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
nullorundefined. 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
undefinedvalue has a special type,undefined. No other value has the typeundefined, not evennull.>
let notDefined: undefined = undefined;notDefined;Result:
undefined
>
let notDefined: undefined = null;notDefined;Result:
type error: Type 'null' is not assignable to type 'undefined'.
Types other than
undefinedcan never have the valueundefined. 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'.
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:
5
>
let numberMaybe: number | undefined = undefined;numberMaybe;Result:
undefined
>
let possiblyBoolean: boolean | undefined = null;possiblyBoolean;Result:
type error: Type 'null' is not assignable to type 'boolean | undefined'.
When we allow
undefinedin this way, it's still tightly controlled. For example, normally we can't assign astring | undefinedto astring.>
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'.
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'
One final note about TypeScript's
--strictNullChecksoption, which changes type checking fornullandundefined. In this TypeScript course,--strictNullChecksis 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.