Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.4Type guards and discriminated unions

State models

A discriminated union gives every variant a shared literal property. It is an excellent way to model a request, a screen or a result that can be in one of several clearly different states.

TypeScript
type Result =
  | { kind: "success"; data: string }
  | { kind: "failure"; message: string };

Exhaustive handling

Use switch on the discriminant. When all cases are handled, TypeScript narrows the corresponding object to exactly the properties available in that case. A final never check can make newly added variants impossible to overlook.

Feedback 👍
Comments are sent via email to me.