TypeScript · Senior · Question 7 of 75

Why are branded types needed?

type UserId = string & { readonly __brand: 'UserId' };

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.

Further reading

Problem with a question

TypeScript · Senior · question 7

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz