Cover image for Null and undefined in Typescript - short explanation

Null and undefined in Typescript - short explanation

ari_o profile image Arika O ・1 min read

Typescript has two special types, null and undefined. They have the values null and undefined respectively. With Javascript, it is not possible to explicitly name these types and operations using these two values are one of the most common reason for runtime errors. We sometimes want variables in our code to hold undefined or null values but many times this happens by mistake.

By default, in Typescript null and undefined are assignable to anything, meaning they can be valid values of every type we want to use. Like in the example below:

Alt Text

If we are going to use the --strictNullChecks mode, the examples above will throw and error and the only types we can assign these two to are null, undefined and any. Undefined behaves a bit special and can be assigned to the type void too.

Alt Text

Photo source: Annie Spratt/ @anniespratt on Unsplash


Editor guide