Lesson 22 of 55
15 mins readPython Discriminated (Tagged) Unions
In Plain English
Discriminated unions use a common literal property (like kind, type, or status) to distinguish between object variants with absolute type safety.
Core Rules to Remember

Discriminant Tag: A shared literal property used in switch statements to narrow shapes.

Exhaustiveness: Guarantees every possible state variant is handled.
Live Interactive Example
Hit Run Code to see it livePattern Matching with Discriminated Unions
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Output Console
Click "Run Code" to view the rendered output.
How it works: Inside each case block, TypeScript knows the exact variant, safely unlocking progress or data.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Calculate Shape Geometry
Define type Circle = { kind: "circle"; radius: number } and type Rectangle = { kind: "rectangle"; width: number; height: number }.
Define type Shape = Circle | Rectangle.
Write function getArea(s: Shape): number (for circle: 3.14 * r * r, for rectangle: width * height).
Print getArea({ kind: "rectangle", width: 4, height: 5 }).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.