typestar

Generics in TypeScript

Functions and types that work over any type.

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

function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

interface Box<T> {
  value: T;
  map<U>(fn: (value: T) => U): Box<U>;
}

const names = pluck([{ id: 1, name: "ada" }], "name");

How it works

  1. <T> makes the input and output types related.
  2. K extends keyof T constrains a key parameter.
  3. T[K] indexes the type to get the value type.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
299
Tokens
121
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 1 of 4 in Type parameters, step 1 of 20 in Generics.

Next →

Generics in other languages