← Back to TypeScript Course | Chapter 2: Basic Types | Lesson 4 of 11

TypeScript Object Types

An object type describes the shape of an object directly, listing its property names and types, without needing a separate interface or type alias.

Basic Object Types

An object type literal lists property names and their types directly in the annotation, such as { name: string; age: number }, letting TypeScript check that a value has exactly the described shape without declaring a separate interface or type alias.

Example: Basic Object Types

typescript
let user: { name: string; age: number } = { name: "Neha", age: 28 };
console.log(user);

Optional Properties

Adding a question mark after a property name, like darkMode?: boolean, marks it optional so a matching value may omit that property entirely, and TypeScript treats its type as including undefined when the property is accessed.

Example: Optional Properties

typescript
let settings: { darkMode?: boolean } = {};
console.log(settings.darkMode); // undefined, since darkMode was omitted
settings = { darkMode: true };
console.log(settings.darkMode);

Readonly Properties

Prefixing a property with readonly prevents it from being reassigned after the object is created, which is useful for values like identifiers or coordinates that should never change once set, while other properties on the same object can still be updated normally.

Example: Readonly Properties

typescript
let point: { readonly x: number; y: number } = { x: 5, y: 10 };
// point.x = 99; // rejected: x is readonly
point.y = 20;
console.log(point);

Index Signatures in Object Types

An index signature such as [key: string]: number lets an object type accept any number of properties whose names aren't known ahead of time, as long as every value matches the declared type, which is useful for dictionaries and lookup tables.

Example: Index Signatures in Object Types

typescript
let scores: { [key: string]: number } = {};
scores["math"] = 90;
scores["science"] = 85;
console.log(scores);

Nested Object Types

Object types can nest other object types as property values, so a type like { address: { city: string; zip: string } } describes structured data with multiple levels, and each nested property is checked with the same strictness as a top-level one.

Example: Nested Object Types

typescript
let profile: { address: { city: string; zip: string } } = {
  address: { city: "Pune", zip: "411001" },
};
console.log(profile.address.city);
🔒

Chapter Quiz — Complete all 11 topics to unlock

0/11 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.