typestar

Constraints and defaults in TypeScript

A type parameter can be bounded, and can have a default.

interface Paged<Item, Meta extends object = { page: number }> {
  rows: Item[];
  meta: Meta;
}

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

function makeStore<Value, Key extends string = string>() {
  const rows = new Map<Key, Value>();
  return {
    set(key: Key, value: Value) {
      rows.set(key, value);
      return rows.size;
    },
    get: (key: Key) => rows.get(key),
  };
}

const page: Paged<string> = { rows: ["a"], meta: { page: 1 } };
const store = makeStore<number, "a" | "b">();
store.set("a", 1);
console.log(longest([1, 2], [1]), page.meta.page, store.get("a"));

How it works

  1. extends bounds what may be passed.
  2. = T supplies a default when it cannot be inferred.
  3. Constraints are what let the body use the parameter.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
609
Tokens
216
Three-star pace
100 tpm

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

Type this snippet

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

← Previous Next →