Nullable types and optional parameters/properties (TypeScript)
An overview of how TypeScript deals with null, undefined and optional parameters/properties
Nullable types
Two special types: null
and undefined
- Treated as different from each other, because that's what JavaScript does as well
- By default, assignable to anything, but this can be changed by enabling the
--strictNullChecks
flag- Recommended to enable this, allow type checking to prevent a lot of potential runtime errors
Example without --strictNullChecks
:
Example with --strictNullChecks
:
Optional chaining
(introduced in TypeScript 3.7)
Operator ?
that allows to stop evaluation when something is null
or undefined
Motivation: accessing instance.prop.otherProp.nextProp
where at each level the property may be null
or undefined
(leading to runtime errors if we fail to check for it)
Example:
Note that, if evaluation stops because something is null
, the result is still undefined
Non-null assertion operator
Operator !
that allows to let TypeScript know you are sure that a certain value is not null
or undefined
(useful in situations where the code is too complex for TypeScript to figure this out by itself)
Example (with --strictNullChecks
):
Optional parameters
If --strictNullChecks
is enabled, making a parameter optional automatically adds | undefined
to its type
Example without --strictNullChecks
:
Example with --strictNullChecks
:
Note: an optional parameter is not completely the same as a parameter that needs to be provided but can be undefined!
You can use this to force the code using your function to be very explicit about passing in undefined
Optional properties
Example without --strictNullChecks
:
Example with --strictNullChecks
: