typestar

Inference in TypeScript

Where TypeScript works the type out, and how to help it.

function pick<const T extends readonly string[]>(values: T): T[number] {
  return values[0]!;
}

function withDefault<T>(value: T | undefined, fallback: NoInfer<T>): T {
  return value ?? fallback;
}

function pair<A, B = A>(first: A, second: B): [A, B] {
  return [first, second];
}

const chosen = pick(["go", "ts"]); // "go" | "ts", not string
const seconds = withDefault(undefined as number | undefined, 60);
const mixed = pair("a", 1);
const same = pair("a", "b");

console.log(chosen, seconds, mixed[1], same[1]);

How it works

  1. Inference flows from the arguments, left to right.
  2. A const type parameter keeps literals narrow.
  3. NoInfer stops one position driving the inference.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
513
Tokens
157
Three-star pace
100 tpm

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

Type this snippet

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

← Previous Next →