0
0
Typescriptprogramming~5 mins

Nested object types in Typescript

Choose your learning style9 modes available
Introduction

Nested object types help you describe objects inside other objects clearly. This makes your code easier to understand and safer to use.

When you have a user object that contains an address object inside it.
When you want to describe a product with details like price and manufacturer info inside it.
When you need to model a blog post that has an author object with name and contact info.
When you want to organize settings where some settings are grouped inside others.
Syntax
Typescript
type Outer = {
  inner: {
    property1: type1;
    property2: type2;
  };
};

You define an object type inside another by writing one object type inside the other.

Each nested object can have its own properties and types.

Examples
This defines a User with a nested address object that has street and city.
Typescript
type User = {
  name: string;
  address: {
    street: string;
    city: string;
  };
};
Product has a nested details object with price and manufacturer info.
Typescript
type Product = {
  id: number;
  details: {
    price: number;
    manufacturer: string;
  };
};
BlogPost includes an author object with name and email.
Typescript
type BlogPost = {
  title: string;
  author: {
    name: string;
    email: string;
  };
};
Sample Program

This program defines a Person type with a nested contact object. It creates a person and prints the name, email, and phone.

Typescript
type Person = {
  name: string;
  contact: {
    email: string;
    phone: string;
  };
};

const person: Person = {
  name: "Alice",
  contact: {
    email: "alice@example.com",
    phone: "123-456-7890"
  }
};

console.log(`Name: ${person.name}`);
console.log(`Email: ${person.contact.email}`);
console.log(`Phone: ${person.contact.phone}`);
OutputSuccess
Important Notes

You can nest objects as deep as you want, but keep it simple to avoid confusion.

Using nested types helps catch mistakes early because TypeScript checks the structure.

Summary

Nested object types describe objects inside other objects.

They make your data structure clear and safe.

Use them when your data naturally groups inside other data.