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
- Inference flows from the arguments, left to right.
- A
consttype parameter keeps literals narrow. NoInferstops one position driving the inference.
Keywords and builtins used here
ABNoInferTasconstextendsfunctionnumberreadonlyreturnstring
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.
Step 3 of 4 in Type parameters, step 3 of 20 in Generics.