TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Type checks

You can move runtime errors to type errors with generics.

const div = (dividend: number, divisor: number) =>
  dividend / divisor

div(1, 0)
// ⛔️ Infinity
type NonZero<Number extends number> = Number extends 0 ? "cannot be 0" : Number

const div = <Divisor extends number>(dividend: number, divisor: NonZero<Divisor>) =>
  dividend / divisor

div(1, 0)
// ✅ Does not compile
// Argument of type '0' is not assignable to parameter of type '"cannot be 0"'

declare function gimmeANumber(): number
div(1, gimmeANumber())
// ⛔️ gimmeANumber() could return 0