How to Check if an Object Has a Property in TypeScript

Recently, I was working on a feature using TypeScript that required displaying user details retrieved from an external API. In that, I got an unexpected error of undefined values for some optional fields. For this, it was required to check whether those properties actually existed on the object before using them.

TypeScript provides several ways to handle this, but choosing the right one depends on the situation. From the in operator and hasOwnProperty to optional chaining and custom type guards, each method offers different levels of security.

In this tutorial, I’ll explain how to check if an object has a property in TypeScript using all possible ways in the examples below.

Why Checking Object Properties is Important in TypeScript?

Before we get into the methods, let’s discuss why it’s important to check if an object has a property. In TypeScript, objects are often used to store and manipulate data. Ensuring that an object has a specific property can prevent runtime errors and improve the robustness of your code. This is particularly essential when dealing with data from external sources, such as APIs or user input.

Using the in Operator to Check Object Property in TypeScript

The in operator is one of the simplest ways to check if an object has a property. It checks for the presence of a property in the object or its prototype chain. Here’s how you can use it:

interface Employee {
    name: string;
    position: string;
    salary?: number;
}

const employee: Employee = {
    name: "John Doe",
    position: "Software Engineer"
};

if ("salary" in employee) {
    console.log("Salary is defined.");
} else {
    console.log("Salary is not defined.");
}

In this example, we check if the salary property exists in the employee object. Since salary is optional, the in operator helps us determine its presence.

Check out: Check if an Object is a String in TypeScript

Using the hasOwnProperty Method to Check Object Property in TypeScript

The hasOwnProperty method checks if the object itself (not its prototype chain) has a specific property. This method is useful when you want to ensure that the property is not inherited.

interface Car {
    make: string;
    model: string;
    year?: number;
}

const car: Car = {
    make: "Tesla",
    model: "Model S"
};

if (car.hasOwnProperty("year")) {
    console.log("Year is defined.");
} else {
    console.log("Year is not defined.");
}

Output:

Check Object property in Typescript

Here, we check if the year property exists in the car object. Since the year is optional and not defined, the output will be “Year is not defined.”

Using Object.prototype.hasOwnProperty.call Method

For added safety, especially when dealing with objects that might have overridden the hasOwnProperty method, you can use Object.prototype.hasOwnProperty.call.

interface City {
    name: string;
    population?: number;
}

const city: City = {
    name: "Los Angeles"
};

if (Object.prototype.hasOwnProperty.call(city, "population")) {
    console.log("Population is defined.");
} else {
    console.log("Population is not defined.");
}

Output:

Check Typescript object property

This method ensures that you are calling the original hasOwnProperty method, avoiding any potential issues with overridden methods.

Using TypeScript’s Type Guards

TypeScript provides type guards to help you narrow down the type within a conditional block. This is particularly useful when dealing with complex objects.

interface User {
    username: string;
    email?: string;
}

const user: User = {
    username: "johndoe"
};

function hasEmail(user: User): user is User & { email: string } {
    return "email" in user;
}

if (hasEmail(user)) {
    console.log(`Email: ${user.email}`);
} else {
    console.log("Email is not defined.");
}

Output:

Method to Check Typescript object property

In this example, we define a type guard hasEmail to check if the email property exists in the user object. This approach provides type safety and clarity in your code.

Check Out: Check if a Value Exists in an Enum in TypeScript

Using Optional Chaining

Optional chaining is a newer feature in TypeScript that allows you to safely access deeply nested properties. If any part of the chain is null or undefined, it short-circuits and returns undefined.

interface Product {
    name: string;
    details?: {
        price?: number;
    };
}

const product: Product = {
    name: "Laptop"
};

const price = product.details?.price;
if (price !== undefined) {
    console.log(`Price: ${price}`);
} else {
    console.log("Price is not defined.");
}

Output:

Check Object property in Typescript using chaining

Here, we use optional chaining to check if the price property exists within the details object of the product. This approach is concise and avoids runtime errors.

Check out: Optional Parameters in TypeScript Interfaces

Real-World Example: API Data Handling

Let’s consider a real-world scenario where you are fetching data from an API and need to check for the presence of certain properties.

interface WeatherData {
    temperature: number;
    humidity?: number;
    windSpeed?: number;
}

async function getWeatherData(city: string): Promise<WeatherData> {
    const response = await fetch(`https://api.weather.com/v3/wx/conditions/current?city=${city}&apiKey=your_api_key`);
    const data = await response.json();
    return data;
}

async function displayWeather() {
    const weatherData = await getWeatherData("New York");

    console.log(`Temperature: ${weatherData.temperature}`);

    if ("humidity" in weatherData) {
        console.log(`Humidity: ${weatherData.humidity}`);
    } else {
        console.log("Humidity data is not available.");
    }

    if (weatherData.hasOwnProperty("windSpeed")) {
        console.log(`Wind Speed: ${weatherData.windSpeed}`);
    } else {
        console.log("Wind Speed data is not available.");
    }
}

displayWeather();

In this example, we fetch weather data for New York City from an API and check for the presence of humidity and windSpeed properties. Using both the in operator and hasOwnProperty method ensures that we handle the data correctly.

Conclusion

In this tutorial, we learned how to check if an object has a property in TypeScript. We discussed various approaches, including the use of the in operator, hasOwnProperty, optional chaining, and type guards to check object properties.

By applying these methods, you can avoid common runtime errors and handle dynamic data more effectively in your TypeScript applications.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.