Learn/TypeScript/14. Types and generics
Lesson 14 of 15
Sign in

TypeScript, lesson 14

Types and generics

TypeScript's signature feature is its type system: expressive enough to describe how real JavaScript code behaves, and lightweight enough that most of it is inferred. This lesson covers the pieces that make the biggest difference in everyday code.

Generic functions

Suppose you want a function that returns the first element of any array. Using any would lose the element type. A type parameter keeps it:

<T> declares a type variable. Each call fills it in, usually by inference from the arguments. Generic functions often take callbacks, and the type flows into them too:

Constraints and keyof

extends limits what a type parameter may be, so you can use its members:

keyof T is the union of 's property names. Combined with a constraint, it makes property access type-safe:

2 exercises to try what you just read.

Exercise 1

Generic helpers

Press Ctrl Enter or Check to test your code.

Exercise 2

Account events

Press Ctrl Enter or Check to test your code.

T

T[K] is an indexed access type: "the type of property K of T".

Discriminated unions

When data comes in several variants, give each variant a literal kind property and combine them in a union:

Inside each case, TypeScript knows exactly which variant you have. The default branch is an exhaustiveness check: after all variants are handled, shape has the type never (no possible value). If someone adds { kind: "triangle" } to Shape later, the assignment to never becomes a type error that points at every switch that needs updating.

Utility types

TypeScript ships generic types that transform other types:

UtilityMeaning
Partial<T>every property optional (good for "update" objects)
Required<T>every property required
Readonly<T>every property read-only
Pick<T, "a" | "b">only the listed properties
Omit<T, "a">all properties except the listed ones
Record<K, V>an object with keys K and values V
ReturnType<F>the return type of a function type

Remember that all of this is erased at run time. Types describe your values; they do not check input that arrives from outside. Validate that input with ordinary code, then let the types carry the guarantees through the rest of the program.

Further reading

  • TypeScript Handbook: Generics
  • TypeScript Handbook: Keyof Type Operator
  • TypeScript Handbook: Narrowing, discriminated unions
  • TypeScript Handbook: Utility Types

Write two generic functions:

  • maxBy<T>(items: T[], score: (item: T) => number): T | undefined returns the item with the highest score (the first one on a tie), or undefined for an empty array.
  • countBy<T>(items: T[], key: (item: T) => string): Map<string, number> counts how many items produce each key, keeping keys in first-seen order.

The given program uses them on two different types. The input's first line is a list of words; every following line is a player NAME TEAM POINTS. It prints the longest word (or - if there are none), the top player, and the number of players per team.

Sample input:

Sample output:

A bank account processes a list of events. Model them with a discriminated union:

Each input line is one event: deposit 100, withdraw 30, transfer 20 bob or interest 5. The balance starts at 0. Write parseEvent(line: string): Event and apply(balance: number, event: Event): number, with a switch on kind that includes a never exhaustiveness check:

  • deposit adds the amount; interest adds that percentage of the current balance;
  • withdraw and transfer subtract the amount, but if the balance is too small the event is rejected: the balance stays the same and the program prints rejected: LINE.

For accepted transfers, print sent AMOUNT to NAME. At the end print balance: B with two decimals.

Sample input:

Sample output:

function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first([3, 1, 2]);        // T is inferred as number, so n: number | undefined
const s = first(["a", "b"]);       // s: string | undefined
function sumBy<T>(items: T[], value: (item: T) => number): number {
  let total = 0;
  for (const item of items) total += value(item);
  return total;
}

sumBy([{ price: 3 }, { price: 4 }], (x) => x.price);   // 7, and x is typed
function longest<T extends { length: number }>(a: T, b: T): T {
  return b.length > a.length ? b : a;
}
longest("pear", "banana");   // works for strings
longest([1, 2], [3]);        // and for arrays
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

const pets = [{ name: "Rex", age: 4 }, { name: "Tom", age: 2 }];
pluck(pets, "name");    // string[]
pluck(pets, "colour");  // error: "colour" is not a key of the pet type
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;   // narrowed to the circle variant
    case "square":
      return shape.side ** 2;
    default: {
      const unreachable: never = shape;     // error if a variant is not handled
      throw new Error(`unknown shape ${JSON.stringify(unreachable)}`);
    }
  }
}
interface User { id: number; name: string; email: string }
type UserPreview = Pick<User, "id" | "name">;
function update(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}
kiwi banana fig
ana red 12
bo blue 30
cy red 7
longest word: banana
top player: bo (30)
red: 2
blue: 1
type Event =
  | { kind: "deposit"; amount: number }
  | { kind: "withdraw"; amount: number }
  | { kind: "transfer"; amount: number; to: string }
  | { kind: "interest"; percent: number };
deposit 100
transfer 30 bob
withdraw 500
interest 10
sent 30 to bob
rejected: withdraw 500
balance: 77.00