TypeScript · Senior · Question 7 of 75
Why are branded types needed?
type UserId = string & { readonly __brand: 'UserId' };- ✓Correct answer: To distinguish structurally identical types, e.g.
UserIdandOrderId - 2To add a
__brandproperty to all strings at runtime - 3To speed up the compiler's comparison of string types
Explanation
Structural typing considers all strings compatible, so deleteUser(orderId) compiles. A brand is a fake property that exists only in types; the value is created by a constructor function with a check (toUserId(s): UserId). This emulates nominal typing.