Make illegal states unrepresentable: unions over flags, parse don't validate, smart constructors
#Name alternatives and tagged variants (Types & syntax) shows how to write a union; this entry uses unions and validated constructors to design a model in which nonsense combinations cannot be built. Optional fields and boolean flags allow combinations that mean nothing, such as a contact with neither an email nor a phone, or verified: true with no date. Replace each such group with a union that lists only the valid shapes (Reach in the example). Wrap values that need checking in a class with a private constructor and a static parse, so every Email in the program has passed it. "Parse, don't validate" means doing this once at the boundary: loose input goes in, and a typed Contact or an error comes out, so later code never checks again.
Complete program
Complete program.
In practice: when you write a comment such as "set only when X", make it a union variant instead. Keep the loose type only for input, parse it at the edge (an API handler, a form), and pass the precise type everywhere else.
private on a constructor is compile-time only; #value is a real JavaScript private field, so the value cannot be read or forged from outside at run time either.
A branded string with a parse function is a lighter alternative to a class when instances need no methods.
For input schemas, Zod 4 (zod 4.6.7) parses unknown data into such types; z.discriminatedUnion builds the unions.