Loading...
JavaScript, React, TypeScript 등 학습하며 정리
discriminated union으로 안전하게 분기
클릭하여 복사
1type Shape =
2 | { kind: 'circle'; radius: number }
3 | { kind: 'rect'; width: number; height: number }
4 | { kind: 'square'; size: number };
5
6function area(shape: Shape) {
7 switch (shape.kind) {
8 case 'circle': return Math.PI * shape.radius ** 2;
9 case 'rect': return shape.width * shape.height;
10 case 'square': return shape.size ** 2;
11 }
12}