Backbencher.dev

Nested Object Types in TypeScript

Last updated on 8 Jan, 2023

We can define the structure of a nested object using TypeScript.

const student: {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
    pin: number;
  };
};

Above type defines structure of an object that has a nested object field address.

Here is a valid student.

const student: {
  name: string;
  age: number;
  address: {
    street: string;
    city: string;
    pin: number;
  };
} = {
  name: "Joby",
  age: 23,
  address: {
    street: "Stoney Peak",
    city: "San Diego",
    pin: 92128,
  },
};

Any invalid value or property results in error.

Invalid attribute
--- ○ ---
Joby Joseph
Web Architect