TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Numbers with units (2)

@mohaalakSuggest 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 extends string> = Type & { readonly [brand]: { [K in Brand]: true }}

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

type Composed = Brand<number, "Positive"> & Height // 👈 This also works