TypeScript Object Types
In this page:
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
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
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
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
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
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: