Skip to content

Nested Object types

von Schappler edited this page Oct 18, 2024 · 2 revisions

Creating nested object types

To understand how nested object types work, let's move back to the snippet of code where the type Person was created:

type Person = {
  name: string;
  age: number;
  isAdult: boolean;
};

On that type, let's implement one more property which is related to a person, their address. Well, normally a person address would not be represented by one of the basic types we have mentioned before. This is most of the times, represented by another object, with properties such as: street, zipcode, number, city, among others.

This is then a good opporunity to make use of nested types to implement this address property for Person. This can be done in two different ways:

  1. Creating it directly inside the Person type, like displayed below:

    type Person = {
      name: string;
      age: number;
      isAdult: boolean;
      address: {
        street: string;
        city: string;
        country: string;
      };
    };
  2. Creating the custom type Address and making use of this right inside the Person type

    This approach is commonly used in situations where a type definition may be necessary into other parts of your code, as well as to provide some extra flexiblity.

    type Address = {
      street: string;
      city: string;
      country: string;
    };
    
    type Person = {
      name: string;
      age: number;
      isAdult: boolean;
      address: Address;
    };
    
    type Company = {
      owner: string;
      address: Address;
    };
Clone this wiki locally