Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Objects, interfaces and narrowing

By the end of this chapter, you'll be able to

  • Describe the shape of an object with a type or an interface
  • Use optional and read-only properties
  • Narrow a type with typeof, in and equality checks
  • Model variants with a discriminated union and check that no case is forgotten

Describe an object

An interface (or a type alias) gives the name and type of each property:

interface Product {
  readonly id: number;
  name: string;
  price: number;
  discount?: number;
}

const wrap: Product = { id: 1, name: "Wax print wrap", price: 8000 };
const bag: Product = { id: 2, name: "Raffia bag", price: 12000, discount: 0.1 };

function finalPrice(p: Product): number {
  return p.discount === undefined ? p.price : Math.round(p.price * (1 - p.discount));
}

console.log(finalPrice(wrap), finalPrice(bag));
8000 10800
  • discount?: makes the property optional: its type is then number | undefined.
  • readonly forbids changing id after creation.
  • interface Product { … } and type Product = { … } are almost equivalent for describing an object. A simple convention: interface for objects, type for unions and the rest.

TypeScript checks every object and every access:

interface Product {
  name: string;
  price: number;
}
const item: Product = { name: "Mango" };
TS2741: Property 'price' is missing in type '{ name: string; }' but required in type 'Product'.
interface Product {
  name: string;
  price: number;
}
const mango: Product = { name: "Mango", price: 300 };
console.log(mango.pricee);
TS2551: Property 'pricee' does not exist on type 'Product'. Did you mean 'price'?

Narrow a type

When a value has a union type, TypeScript only allows what is valid for all the possibilities. To go further, you must test the value: TypeScript follows your test and narrows the type in each branch.

function showQuantity(q: number | string): string {
  if (typeof q === "number") {
    return q.toFixed(1);
  }
  return q.trim();
}

console.log(showQuantity(2.456));
console.log(showQuantity("  3 kg "));
2.5
3 kg

Inside the if, q is a number; after it, it can only be a string. The same mechanism protects against missing values:

interface Customer {
  name: string;
  phone?: string;
}
function dialCode(c: Customer): string {
  return c.phone.slice(0, 4);
}
TS18048: 'c.phone' is possibly 'undefined'.

Handling the case is enough: if (!c.phone) return "unknown"; before the faulty line, and the error goes away.

Discriminated unions

A payment can be made in cash, by card or by mobile money. Each variant has its own information. We describe them as a union of objects that share a literal property, here method: this is a discriminated union.

type Payment =
  | { method: "cash"; amount: number }
  | { method: "card"; amount: number; lastDigits: string }
  | { method: "mobile"; amount: number; provider: string };

function describe(p: Payment): string {
  switch (p.method) {
    case "cash":
      return `${p.amount} FCFA in cash`;
    case "card":
      return `${p.amount} FCFA by card ****${p.lastDigits}`;
    case "mobile":
      return `${p.amount} FCFA via ${p.provider}`;
  }
}

console.log(describe({ method: "card", amount: 15000, lastDigits: "4821" }));
console.log(describe({ method: "mobile", amount: 2500, provider: "Wave" }));
15000 FCFA by card ****4821
2500 FCFA via Wave

In each case, TypeScript knows which variant you are handling: p.provider is only accessible in the "mobile" case.

The function returns the description, which console.log displays.

Step 5 of 5
Text description of the animation
  1. We call describe with a mobile payment.
  2. The switch reads the discriminating property method.
  3. The first case does not match: we move on to the next.
  4. In this case, TypeScript knows p is the mobile variant: p.provider necessarily exists.
  5. The function returns the description, which console.log displays.

Mini-lab: geometric shapesTypeScript

Output

Click “Run”: the TypeScript compiler will be loaded in your browser (about 3 MB the first time). Your code is checked, then run if it has no type error.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the state of a delivery

A delivery is either "preparing", "shipped" (with a tracking number) or "delivered" (with the delivery date, a string). Model this type, then write message(d) which returns “Being prepared”, “Shipped, tracking: …” or “Delivered on …”. Add the exhaustiveness check.

Hint 1
Each variant has a state property with a literal type, plus its own fields.
Hint 2
The default assigns d to a constant of type never.
Show the solution and common mistakes
type Delivery =
  | { state: "preparing" }
  | { state: "shipped"; tracking: string }
  | { state: "delivered"; date: string };

function message(d: Delivery): string {
  switch (d.state) {
    case "preparing":
      return "Being prepared";
    case "shipped":
      return `Shipped, tracking: ${d.tracking}`;
    case "delivered":
      return `Delivered on ${d.date}`;
    default: {
      const missed: never = d;
      return missed;
    }
  }
}

console.log(message({ state: "shipped", tracking: "SN-20391" }));
console.log(message({ state: "delivered", date: "12/11/2026" }));
Shipped, tracking: SN-20391
Delivered on 12/11/2026

Common mistakes:

  • Putting tracking?: string in a single object for all the variants: you would then have to check everywhere whether it exists, and nothing would stop a “delivered” delivery without a date.
  • Writing case "deliverd" with a typo: it is not one of the union's values, and TypeScript refuses it (TS2678).

Summary

  1. 1An interface describes the shape of an object: each property, its type, with ? for optional and readonly for immutable.
  2. 2TypeScript reports missing, extra or misspelled properties.
  3. 3typeof, comparisons and presence checks narrow a union type in each branch.
  4. 4A discriminated union models variants that share a literal property.
  5. 5A default that assigns the value to never guarantees that no variant is forgotten.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.