How to Correctly Check Undefined in TypeScript
To check for undefined
values in TypeScript, you need to use the strict equal operator against the undefined
keyword.
type AuthorHandle = string | undefined
const twitter: AuthorHandle
// ❌ This will throw an error (Cannot read properties of undefined)
const formattedHandle: string = twitter.toLowerCase()
// ✔️ Check if variable is not undefined
if (twitter !== undefined) {
const formattedHandle: string = twitter.toLowerCase()
}
In the above example, the if statement is called a type guard. It prevents toLowerCase
being called on undefined
. This way, TypeScript knows that the only other possible type is a string
type.
It is important to keep in mind that in case your variable can be null
, you want to check for a null
value too, as the above code example only caters to undefined
.
type AuthorHandle = string | undefined | null
const twitter: AuthorHandle
// ❌ This will throw an error (Cannot read properties of undefined)
const formattedHandle: string = twitter.toLowerCase()
// ❌ This will throw an error for null (Cannot read properties of null)
if (twitter !== undefined) {
const formattedHandle: string = twitter.toLowerCase()
}
// ✔️ Check if variable is not undefined OR null
if (twitter !== undefined && twitter !== null) {
const formattedHandle: string = twitter.toLowerCase()
}
// Note that null and undefined are not the same thing
undefined === null -> false
If you often have to work with types that can be either undefined
or null
, it is recommended to declare a generic often called Nullable
or Maybe
that can be reused throughout your application.
declare type Nullable<T> = T | undefined | null
// This will now be string | undefined | null
type AuthorHandle = Nullable<string>

Using Optional Chaining
Another approach to safeguard against undefined
values is using optional chaining. Optional chaining lets you use the ?.
notation to only call methods and properties if the variable is not undefined
or null
.
type AuthorHandle = Nullable<string>
const twitter: AuthorHandle
const formattedHandle: string = twitter?.toLowerCase()
This way, you can leave out the if statement, and be sure that your variable is checked against both undefined
and null
.

Tired of looking for tutorials?
You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.
Check out our interactive course to master JavaScript in less time.
Learn MoreRecommended

How to Save Writable Store in Svelte to Local Storage
Learn how to create a persistent store in Svelte

How to Create an Infinite Scroll Component in React
With the help of the Intersection Observer API
