TypeScript Object Types - Object Literals, Optional/Readonly Properties

Master TypeScript object types, optional properties, readonly properties, nested objects, and index signatures!

Introduction

Let's define types for objects in TypeScript!

What You Will Learn

  • Object type literals
  • Optional properties
  • Readonly properties
  • Nested object types

Prerequisites

Object Type Literals!

Define the shape of an object!

let user: { name: string; age: number; isAdmin: boolean } = {
  name: "John",
  age: 30,
  isAdmin: true,
};

Optional Properties!

Use ? for optional properties!

let user: { name: string; age?: number } = {
  name: "John",
};

Readonly Properties!

Use readonly to prevent modification!

let user: { readonly id: number; name: string } = {
  id: 1,
  name: "John",
};
// user.id = 2; // Error!

Nested Objects!

let user: {
  name: string;
  address: {
    city: string;
    zip: string;
  };
} = {
  name: "John",
  address: { city: "NY", zip: "10001" },
};

Index Signatures!

For objects with dynamic keys!

let phoneBook: { [key: string]: string } = {
  John: "555-1234",
  Jane: "555-4321",
};

Best Practices

  1. Prefer interfaces for reusable types: Next module!
  2. Use optional properties carefully: Avoid too many!
  3. Use readonly for immutable fields!

Summary

Object types in TypeScript!

Related Articles

Previous Tutorial

Arrays & Tuples

Next Tutorial

Let's learn interfaces! → Interfaces