TypeScript for real code · Chapter 15 of 36

Rules for T

By the end of this chapter you can put rules on a type parameter: T must have an id, K must be a real key of T, and T has a default when nobody names it. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Generics
  • 4 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.

Why you need this

Ravi's lookup by id works on the menu and on riders, but what comes back is only { id: string }: the price and the bike are gone, so the bill cannot read the price it just found. Anjali wants one helper that reads any field of any object, and another that reads one field from a whole list, with a typo in the field name caught before a customer sees it. Kabir wants every API reply to share one type.

A type parameter from last chapter can be anything at all, so TypeScript lets you do nothing with it that would not work on a number:

function cheaper<T>(a: T, b: T): T {
  return a.price <= b.price ? a : b;
}
$ typecheck demo.ts
demo.ts:2:12 - error TS2339: Property 'price' does not exist on type 'T'.

2   return a.price <= b.price ? a : b;
             ~~~~~

Bunty's way round it is a plain parameter type instead of T. It compiles, but it is exactly what broke Ravi's lookup:

type Snack = { name: string; price: number; veg: boolean };
const bun: Snack = { name: 'bun maska', price: 30, veg: true };
const puff: Snack = { name: 'egg puff', price: 25, veg: false };

function cheaperPlain(a: { price: number }, b: { price: number }) {
  return a.price <= b.price ? a : b;
}

console.log(cheaperPlain(bun, puff).name);
$ typecheck demo.ts
demo.ts:9:37 - error TS2339: Property 'name' does not exist on type '{ price: number; }'.

The snack went in whole and came out as { price: number }.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    getProp: only real keys, and the right type back

    getProp(obj, key) reads one field of an object: getProp(chai, 'price') is 40 and getProp(bun, 'name') is 'bun maska'.

    Replace the anys with two type parameters: T for the object, and K for the key, with the rule that K is one of the keys of T. Return T[K]. Then, for a MenuItem, getProp(chai, 'price') has the type number, getProp(chai, 'name') has the type string, and getProp(chai, 'prise') is a type error.

  2. Task 2

    pluck: one field from every item in a list

    pluck(list, key) returns that one field from every item, in order: pluck(menu, 'name') is ['masala chai', 'bun maska'], pluck(menu, 'price') is [40, 30], and an empty list gives [].

    Use the same two type parameters as getProp, so pluck(menu, 'name') has the type string[], pluck(menu, 'price') has the type number[], pluck(menu, 'bike') is a type error (a menu item has no bike), and pluck(riders, 'bike') is fine.

  3. Task 3

    Reply: any type of data, a string by default

    Every reply from Tapri's API has ok and data. Give Reply a type parameter T for the type of data, with string as its default: a plain Reply has data of type string, so { ok: true, data: 'Order placed' } is a Reply and { ok: true, data: 42 } is not. Reply<MenuItem[]> has data of type MenuItem[].

    ok stays a boolean whatever T is, so Reply<number> has ok of type boolean.

  4. Task 4 · interview question

    Interview: findById, keep the full type of what it finds

    findById(list, id) finds the item with that id, or undefined: findById(menu, 'm2') is the bun maska item, and findById(menu, 'm9') is undefined. Today it returns only { id: string }, so the price and the bike are lost.

    Make it generic: T extends { id: string }, list is a T[], and the result is T | undefined. Then findById(menu, 'm1') has the type MenuItem | undefined, findById(riders, 'r1') has the type Rider | undefined, and findById(['masala chai', 'bun maska'], 'm1') is still a type error, because a list of names has no ids. This task also checks the whole of exercise.ts: it must have no type errors anywhere. Dev will ask what the difference is between a parameter typed { id: string }[] and a type parameter with that rule.

What you will learn

  • Constraints: T extends { price: number }, any type, as long as it has a numeric price.
  • keyof and indexed access: the union of a type's keys, and the type stored under one of them.
  • Defaults: <T = number>, the type used when nobody names one.

More in Generics

Build "Rules for T" yourself

Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.