DEV Community

Cover image for Null and undefined in Typescript - short explanation
Arika O
Arika O

Posted on • Edited on

4 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay