πŸ’‘ This page contain affiliate links. By making a purchase through them, we earn a commission at no extra cost to you.

How to Correctly Check Undefined in TypeScript

Ferenc Almasi β€’ 2022 September 21 β€’ πŸ“– 2 min read

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()
}
Copied to clipboard!

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
Copied to clipboard!

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>
Copied to clipboard!
Looking to improve your skills? Master TypeScript from start to finish.
Master TypeScript

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()
Copied to clipboard!

This way, you can leave out the if statement, and be sure that your variable is checked against both undefined and null.

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended