Object types
Overview
Objects are everywhere in JavaScript: users, products, settings, API responses. Object types describe their shape — which properties they have and what type each one holds — so TypeScript can check every object you create and every property you read.
Writing an object type
const user: { name: string; age: number; email: string } = {
name: "Asha",
age: 29,
email: "asha@example.com",
};Usually you give the shape a name with a type alias so it can be reused:
type User = {
name: string;
age: number;
email: string;
};
function greet(user: User): string {
return `Hello, ${user.name}`;
}Properties are separated by semicolons (commas also work). Now TypeScript checks both directions:
const u: User = { name: "Asha", age: 29 };
// error TS2741: Property 'email' is missing in type '{ name: string; age: number; }' but required in type 'User'.
greet(u);
u.phone;
// error TS2339: Property 'phone' does not exist on type 'User'.Optional properties
Add ? for properties that may be missing:
type User = {
name: string;
nickname?: string; // string | undefined
};
const a: User = { name: "Asha" }; // ✓
const b: User = { name: "Benedict", nickname: "Ben" }; // ✓Because an optional property might be undefined, TypeScript makes you check before using it:
a.nickname.toUpperCase();
// error TS18048: 'a.nickname' is possibly 'undefined'.
a.nickname?.toUpperCase(); // optional chaining
a.nickname ?? a.name; // fallbackreadonly properties
readonly stops a property from being reassigned after the object is created:
type Product = {
readonly sku: string;
price: number;
};
const p: Product = { sku: "LMP-01", price: 29.99 };
p.price = 24.99; // ✓
p.sku = "X";
// error TS2540: Cannot assign to 'sku' because it is a read-only property.Like readonly arrays, it’s a compile-time check — great for IDs and other values that should never change.
Nested objects, arrays and methods
Object types can contain anything:
type Order = {
id: string;
customer: { name: string; email: string }; // nested object
items: { sku: string; quantity: number }[]; // array of objects
total(): number; // method
onShip?: (date: Date) => void; // optional callback property
};When a nested shape is reused, give it its own name (type Customer = { … }) and refer to it — your types read like a small data model of your application.
Structural typing: shape is what counts
In languages like Java or C#, a value fits a type only if it was declared as that type. TypeScript is structural: a value fits if it has the right shape.
type Point = { x: number; y: number };
function show(p: Point) {
console.log(p.x, p.y);
}
const p3 = { x: 1, y: 2, z: 3 };
show(p3); // ✓ — p3 has x and y; the extra z doesn't matterThat matches how JavaScript works — functions care about the properties they use — and it means you rarely need to convert between types that have the same shape.
Excess property checks
There’s one exception. When you write an object literal directly where a type is expected, TypeScript also complains about properties the type doesn’t have:
show({ x: 1, y: 2, z: 3 });
// error TS2353: Object literal may only specify known properties, and 'z' does not exist in type 'Point'.Why the difference? A fresh literal isn’t used anywhere else, so an unknown property is almost certainly a typo:
const lamp: Product = { sku: "LMP-01", pirce: 29.99 };
// error TS2561: Object literal may only specify known properties, but 'pirce' does not exist in type 'Product'. Did you mean to write 'price'?This check is a big part of why TypeScript catches so many typos.
Empty objects and object
Two types look similar but mean different things:
{}means “any value exceptnullandundefined” — including strings and numbers. Rarely what you want.objectmeans “any non-primitive value” (objects, arrays, functions).
For “an object with unknown properties”, use Record<string, unknown> (Index signatures and records).
Destructuring with types
You can destructure typed objects in parameters; the type annotation goes after the whole pattern:
function format({ name, nickname }: User): string {
return nickname ? `${name} (${nickname})` : name;
}Remember: list the properties, mark the optional (
?) and fixed (readonly) ones, and let structural typing and excess property checks do the rest.
A product catalogue
Define a Product type with a readonly sku (string), name (string), price (number), an optional salePrice (number), tags (array of strings) and a nested dimensions object with width, height and depth in cm. Write describe(product: Product): string that returns e.g. Desk Lamp — 24.99 (was 29.99) [lighting, home] when there’s a sale price and Notebook — 3.50 [paper] otherwise. Write volumeLitres(product: Product): number (cm³ ÷ 1000). Create two products and print the results. Then show with // @ts-expect-error lines that (a) sku can’t be reassigned, (b) a misspelled property pirce in an object literal is rejected.
// 1. The Product type
// 2. describe()
// 3. volumeLitres()
// 4. Two products, and the two @ts-expect-error checks// 1. The Product type
type Product = {
readonly sku: string;
name: string;
price: number;
salePrice?: number;
tags: string[];
dimensions: { width: number; height: number; depth: number };
};
// 2. describe()
function describe(product: Product): string {
const tags = `[${product.tags.join(", ")}]`;
if (product.salePrice !== undefined) {
return `${product.name} — ${product.salePrice.toFixed(2)} (was ${product.price.toFixed(2)}) ${tags}`;
}
return `${product.name} — ${product.price.toFixed(2)} ${tags}`;
}
// 3. volumeLitres()
function volumeLitres(product: Product): number {
const { width, height, depth } = product.dimensions;
return (width * height * depth) / 1000;
}
// 4. Two products, and the two @ts-expect-error checks
const lamp: Product = {
sku: "LMP-01",
name: "Desk Lamp",
price: 29.99,
salePrice: 24.99,
tags: ["lighting", "home"],
dimensions: { width: 15, height: 45, depth: 15 },
};
const notebook: Product = {
sku: "NB-A5",
name: "Notebook",
price: 3.5,
tags: ["paper"],
dimensions: { width: 15, height: 21, depth: 1 },
};
console.log(describe(lamp)); // Desk Lamp — 24.99 (was 29.99) [lighting, home]
console.log(describe(notebook)); // Notebook — 3.50 [paper]
console.log(volumeLitres(lamp)); // 10.125
// @ts-expect-error -- sku is readonly
lamp.sku = "LMP-02";
const typo: Product = {
sku: "X",
name: "X",
// @ts-expect-error -- excess property check catches the typo
pirce: 1,
price: 1,
tags: [],
dimensions: { width: 1, height: 1, depth: 1 },
};
console.log(typo.name);Summary
- An object type lists property names and their types:
{ name: string; price: number }. ?makes a property optional (its type includesundefined);readonlystops reassignment.- TypeScript is structural: any object with the required properties fits, whatever it’s called.
- Object literals written in place get an excess property check, which catches typos in property names.
- Object types can nest, contain arrays, and describe methods.