Null and undefined in Typescript - short explanation
Arika O
Posted on May 25, 2020
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:
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.
Photo source: Annie Spratt/ @anniespratt on Unsplash
Posted on May 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.