Skip to content
Justice Tech School

Discriminated Unions

Give each member a literal kind property. switch on it and TypeScript knows the rest.

Example
type Shape = { kind: "circle"; r: number } | { kind: "sq"; s: number };
function area(s: Shape) {
  switch (s.kind) {
    case "circle": return Math.PI * s.r ** 2;
    case "sq": return s.s ** 2;
  }
}
console.log(area({ kind: "sq", s: 3 }));

Result

9

Exercise

Discriminant name.

type A = { : "a" }

Quiz Test

What identifies each union member?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.