A Shared Field That Tells Branches Apart

Give every branch a shared literal field. Then checking that field narrows the whole object, and the compiler knows exactly which properties are available.

This is the pattern that makes the four states from the React course impossible to get wrong.

Try it

Try to read s.message before the status check and see what happens. Then remove one of the branches from the union and watch the render function stop compiling.

loading editor…

checking…

The last line is the point: a loading state carrying an error message cannot be constructed. In the React course that combination was prevented by discipline. Here it is prevented by the compiler.

Compare with three separate booleans. loading, error and items as three pieces of state allow sixteen combinations, of which perhaps four are meaningful. A discriminated union allows exactly the ones you declared.

This is the same argument as useReducer in the React course, and the same argument as constraints in the SQL course: make the wrong state unrepresentable rather than merely unlikely.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Exhaustiveness →
← Back