Branded types
Branded types in TypeScript enhance type safety by adding a unique identifier to existing types, preventing accidental misuse of values that share the same underlying type. They are particularly useful for distinguishing between similar types, like different kinds of IDs or units of measurement, ensuring that only valid values are assigned to variables.
They let us distinguish between values that share the same primitive type but have different meanings.
Example
type Brand<T, B> = T & { __brand: B };
type UserId = Brand<string, “UserId”>;
type ProductId = Brand<string, “ProductId”>;