TypeScript Tips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Numbers with units (2)

@RiccardoOdone Suggest a tip

You can brand types to distinguish one from the other. Though, if you need to prevent combining types, branding is not a good solution.

const height: number = 2
const weight: number = 3

const format = (height: number, weight: number): string => ""

format(weight, height) // ⛔️ Swapped
declare const brand: unique symbol;
type Brand<Type, Brand> = Type & { readonly [brand]: Brand }

type Height = Brand<number, "Height">
type Weight = Brand<number, "Weight">

const height = 2 as Height
const weight = 3 as Weight

const format = (height: Height, weight: Weight): string => ""

format(weight, height) // ✅ Does not compile
weight + height // ⛔️ Do not use branding if need combining