capypad
0 day streak
typescript / intermediate
Snippet

Discriminated Unions

Discriminated unions use a common literal property (the discriminant) to allow TypeScript to narrow down members of a union safely.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
interface Circle { kind: "circle"; radius: number; }
interface Square { kind: "square"; side: number; }
 
type Shape = Circle | Square;
 
function getArea(s: Shape) {
if (s.kind === "circle") return Math.PI * s.radius ** 2;
return s.side ** 2;
}
Breakdown
1
kind: "circle"
A literal type serving as a unique identifier for the specific interface.
2
type Shape = Circle | Square
Defines a union type that can be either a Circle or a Square.
3
if (s.kind === "circle")
TypeScript narrows the type of 's' to Circle within this block.