TypeScript for real code · Chapter 14 of 36

One function, many types

By the end of this chapter you can write one function that works on lists of anything, and still keeps the exact type of what goes through 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

Bunty is proud of his helpers file: first, pair, groupBy and firstWhere work on orders, names, prices, anything. Then Kabir found a bill that tried to round a menu item's name to two decimal places, and a search for orders by prise that compiled and never found one. Every helper takes and returns any, so nothing that goes through them is checked.

The types you know so far force a choice. Type a helper for Order[] and you need another copy for string[], and another for number[]. Type it any[] and it works on everything, but what comes out is any:

function lastAny(list: any[]): any {
  return list[list.length - 1];
}

const latest = lastAny(['masala chai', 'bun maska']);
console.log(latest.toFixed(2));
$ typecheck demo.ts
No type errors.
$ node demo.ts
file:///workspace/chapters/14-generic-functions/demo.ts:6
console.log(latest.toFixed(2));
                   ^

TypeError: latest.toFixed is not a function

A list of strings went in, and any came out, so every line after that call is unchecked.

What you build: 4 tasks

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

  1. Task 1

    first: keep the type of the list

    first returns the first item of a list, or undefined for an empty list: first([40, 25]) is 40 and first([]) is undefined.

    Replace the anys with a type parameter for the item type, so first([40, 25]) has the type number | undefined, and first(['masala chai', 'bun maska']) has the type string | undefined. The undefined belongs in the return type, because a list can be empty.

  2. Task 2

    pair: keep the types of both values

    pair(a, b) returns the two values as a pair: pair('masala chai', 40) is ['masala chai', 40].

    Use two type parameters, one for each value, so the result of pair('masala chai', 40) has the type [string, number]: after const [item, price] = pair('masala chai', 40), item is a string and price is a number. Write the return type yourself, as a tuple of the two type parameters: left alone, TypeScript infers a list whose items are either type.

  3. Task 3

    groupBy: group any list by a key

    groupBy(list, keyOf) groups the items by the key keyOf gives for each one, keeping their order. For three orders, T1 and T3 with rider Raju and T2 with rider Salma, groupBy(orders, (o) => o.rider) is { Raju: [T1, T3], Salma: [T2] }. groupBy(['cutting', 'large', 'cutting'], (s) => s) is { cutting: ['cutting', 'cutting'], large: ['large'] }, and an empty list gives {}.

    Make it generic in the item type T: list is a T[], keyOf takes a T and returns a string, and the result is a Record<string, T[]>. Then keyOf knows what it gets: grouping orders by o.price is a type error, because an order has no price.

  4. Task 4 · interview question

    Interview: firstWhere, a type parameter instead of any

    firstWhere(list, test) returns the first item that passes the test, or undefined: for three orders T1, T2 and T3 with qty 2, 1 and 6, firstWhere(orders, (o) => o.qty > 5) is the order T3, and firstWhere(orders, (o) => o.qty > 10) is undefined.

    Replace every any with one type parameter T: the list is a T[], test takes a T, and the result is T | undefined, so for orders the result is Order | undefined, and firstWhere(orders, (o) => o.prise > 0) is a type error. Dev will ask what the difference is between a function typed with any and one with a type parameter.

What you will learn

  • Type parameters: a placeholder for a type, written in angle brackets, that links what goes in to what comes out.
  • Inference: TypeScript works the type parameter out from the arguments, so callers rarely write it.
  • Type parameters in callbacks and tuples: a callback that knows what it gets, and a return type that keeps two values apart.

More in Generics

Build "One function, many types" 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.