Open In App

How to Define Interfaces for Nested Objects in TypeScript ?

In TypeScript, defining interfaces for nested objects involves specifying the structure of each level within the object hierarchy. This helps ensure that the nested objects adhere to a specific shape or pattern.

Here are step-by-step instructions on how to define interfaces for nested objects in TypeScript:

Step 1: Identify the Nested Structures Determine the structure of your nested objects. Identify the properties and their types at each level of nesting.



Step 2: Define Interfaces for Innermost Objects Start by creating interfaces for the innermost objects or the leaf nodes of your nested structure. Specify the properties and their types for each inner object.




interface Contact {
    email: string;
    phone: string;
}

Step 3: Move to the Next Level of Nesting If your object has further nesting, move outward to the next level. Create interfaces for the objects that contain the innermost objects, using the previously defined interfaces.






interface Address {
    street: string;
    city: string;
    zipCode: string;
}

Step 4: Continue Defining Interfaces Repeat the process until you reach the top-level object. Create interfaces for each level, incorporating the previously defined interfaces for nested objects.




interface Person {
    name: string;
    age: number;
    contact: Contact;
    address: Address;
}

Step 5: Use the Top-Level Interface Now that you have defined interfaces for all levels, you can use the top-level interface to ensure that any object adheres to the specified nested structure.

Example: In this example, we’ve created interfaces for a Contact with email and phone properties, an Address with street, city, and zipCode properties, and a top-level Person interface that includes a name, age, contact, and address. We then instantiated a Person object (myInfo) with the specified structure.




const myInfo: Person = {
    name: "John Doe",
    age: 25,
    contact: {
        email: "john.doe@example.com",
        phone: "555-1234"
    },
    address: {
        street: "123 Main St",
        city: "Anytown",
        zipCode: "12345"
    }
};


Article Tags :