Object types

Topic 1 of 4 in Objects and functions7 min readIntermediateFree course

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

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
a.nickname.toUpperCase();
// error TS18048: 'a.nickname' is possibly 'undefined'.

a.nickname?.toUpperCase();        // optional chaining
a.nickname ?? a.name;             // fallback

readonly properties

readonly stops a property from being reassigned after the object is created:

TypeScript
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:

TypeScript
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

Types are about shape, not names. With type Point = { x: number; y: number } and function show(p: Point), calling show(p3) with const p3 = { x: 1, y: 2, z: 3 } is OK, because the object has everything Point needs. show({ x: 1 }) fails because y is missing, and show({ x: 1, y: 2, z: 3 }) fails because of the extra z in a fresh literal. Any value with the required properties fits the type — extra properties are fine, missing ones are not. Object literals written directly in place get an extra check for typos (“excess property check”).

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.

TypeScript
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 matter

That 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:

TypeScript
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:

TypeScript
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 except null and undefined” — including strings and numbers. Rarely what you want.
  • object means “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:

TypeScript
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.

Exercise

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.

TypeScript
// 1. The Product type

// 2. describe()

// 3. volumeLitres()

// 4. Two products, and the two @ts-expect-error checks

Summary

  • An object type lists property names and their types: { name: string; price: number }.
  • ? makes a property optional (its type includes undefined); readonly stops 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.