TypeScript's structural type system allows any two types that seem to have the same shape to be assignable to each other. But what if you want to restrict a type to only allow certain values, even if other values happen to have the same structure? Say, marking a difference between sanitized and un-sanitized strings, or positive integers from all numbers?
This need is solvable with a pattern called "branded types", sometimes also called "opaque types". Let's dive into why you'd want to use branded types, how to declare and use them, and some alternatives to the pattern.