Null and undefined in Typescript - short explanation

arikaturika

Arika O

Posted on May 25, 2020

Null and undefined in Typescript - short explanation

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

πŸ’– πŸ’ͺ πŸ™… 🚩
arikaturika
Arika O

Posted on May 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Getting Started with Typescript
typescript Getting Started with Typescript

July 21, 2024

Classes in TypeScript: With Challenges
keyof typeof Object
typescript keyof typeof Object

June 10, 2023

Part 6: Advanced TypeScript Topics
typescript Part 6: Advanced TypeScript Topics

May 23, 2023