You may have faced some issues where your code breaks because an object is undefined. For example, you’re trying to access a property of an object, but that object was never assigned a value.
In such cases, checking if the object is undefined helps prevent runtime errors and keeps your code safe.
In this tutorial, we will learn how to check if object is undefined in TypeScript. We’ll cover different methods and best practices, along with detailed examples, to help you understand how to handle undefined objects in TypeScript effectively.
What Does Undefined Mean in TypeScript?
In TypeScript, undefined is a type that denotes a variable that has not been assigned a value. This is slightly different from null, which is an assignment value that represents the absence of a value or an object. Knowing how to distinguish between these two is crucial for writing robust TypeScript code.
Why is it important to check for Undefined?
When working with APIs or any dynamic data sources, you might encounter situations where certain properties of an object are not available.
For instance, if you are fetching user data from an API and some users do not have a middle name, the middleName property might be undefined. Failing to check for undefined values can lead to runtime errors or unexpected behavior in your application.
Check If an Object Is Undefined in TypeScript
There are several ways to check if an object or a property of an object is undefined in TypeScript. Let’s explore these methods with practical examples.
Using the typeof Operator in TypeScript
The typeof operator is a simple and effective way to check if a variable is undefined. It returns a string indicating the type of the unevaluated operand.
let user: { firstName: string; middleName?: string; lastName: string } = {
firstName: "John",
lastName: "Doe",
};
if (typeof user.middleName === "undefined") {
console.log("Middle name is undefined");
} else {
console.log("Middle name is:", user.middleName);
}In this example, user.middleName is optional and may not be present. Using typeof, we can safely check if it is undefined before attempting to use it.

Check out: Convert an Object to an Array in TypeScript?
Using the === Operator in TypeScript
Another common method is to use the strict equality operator (===). This method is straightforward and checks if a variable is strictly equal to undefined.
if (user.middleName === undefined) {
console.log("Middle name is undefined");
} else {
console.log("Middle name is:", user.middleName);
}This approach is simple and effective for checking undefined values.

Check out: Find an Object in a TypeScript Array
Using Optional Chaining in TypeScript
TypeScript 3.7 introduced optional chaining, which allows you to safely access deeply nested properties without having to check each level explicitly.
let address: { city?: string; state?: string } | undefined;
if (address?.city === undefined) {
console.log("City is undefined");
} else {
console.log("City is:", address.city);
}Optional chaining (?.) provides a concise way to check for nullish values (null or undefined) and can simplify your code significantly.

Check out: Search an Array of Objects by Property in TypeScript
Using the Nullish Coalescing Operator in TypeScript
The nullish coalescing operator (??) is another feature introduced in TypeScript 3.7. It allows you to provide a default value if the variable is null or undefined.
let city: string | undefined;
let cityName = city ?? "Unknown City";
console.log("City:", cityName);In this example, if a city is undefined, cityName will be assigned the value “Unknown City“.

Check out: Sort an Array of Objects by Property in TypeScript
Real-Time Example to Check Undefined Object in TypeScript
Let’s consider a real-world scenario where you are working with user data fetched from an API. You need to display the user’s full name, but some users might not have a middle name.
interface User {
firstName: string;
middleName?: string;
lastName: string;
}
function getFullName(user: User): string {
return `${user.firstName} ${user.middleName ?? ""} ${user.lastName}`.trim();
}
let user1: User = {
firstName: "Jane",
lastName: "Smith",
};
let user2: User = {
firstName: "Robert",
middleName: "John",
lastName: "Johnson",
};
console.log(getFullName(user1)); // Output: "Jane Smith"
console.log(getFullName(user2)); // Output: "Robert John Johnson"In this example, the getFullName function constructs the full name of the user, using the nullish coalescing operator to handle the case where middleName might be undefined.

Check out: Difference Between Record vs Object in TypeScript
Best Practices for Handling Undefined in TypeScript
- Always Initialize Variables: Whenever possible, initialize your variables to avoid unexpected undefined values.
- Use TypeScript’s Type System: Leverage TypeScript’s powerful type system to define optional properties and handle undefined values gracefully.
- Consistent Checks: Use consistent methods for checking undefined values throughout your codebase to improve readability and maintainability.
- Avoid Implicit Any: Ensure that you have strict mode enabled in your tsconfig.json to avoid implicit
anytypes, which can lead to undefined issues.
Conclusion
Checking for undefined values in TypeScript is a common task that can help you avoid many runtime errors and bugs. By using the methods described above, such as the typeof operator, strict equality checks, optional chaining, and the nullish coalescing operator, you can write more robust and error-free code. Always remember to leverage TypeScript’s type system to define optional properties and handle undefined values consistently.
By following these best practices and understanding the various methods for checking for undefined values, you can enhance the reliability and maintainability of your TypeScript applications. Whether you are working with user data, API responses, or any other dynamic data sources, handling undefined values correctly is crucial for building robust software.
You may like to read:
- Check If a Key Exists in a TypeScript Object
- Use TypeScript Enums as Object Keys
- Check if an Object Has a Property in TypeScript

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.