식별된 유니온 기법을 사용하는 경우 아래와 같습니다.
type Shape =
| { kind: 'circle', radius: number }
| { kind: 'rectangle', width: number; height: number }
function getShapeInfo(shape: Shape) {
if (shape.kind === 'circle') {
console.log(shape.radius);
}
if (shape.kind === 'rectangle') {
console.log(shape.width, shape.height);
}
}
일반적으로 공통 속성을 이용하여 값을 식별하고 타입을 좁히게 됩니다.
이를 조금 더 엄격하게 사용할 수 있습니다.
예를 들어 특정 함수에서 union에 정의된 모든 kind
를 처리해야 하는데 사람을 실수로 kind: polygon
이 추가되었을때 해당 함수에 케이스 처리를 누락할 수 있습니다.
type Shape =
| { kind: 'circle', radius: number }
| { kind: 'rectangle', width: number; height: number }
| { kind: 'polygon' };
function getShapeInfo(shape: Shape) {
if (shape.kind === 'circle') {
console.log(shape.radius);
}
if (shape.kind === 'rectangle') {
console.log(shape.width, shape.height);
}
}
위 코드와 같이 polygon
이 추가되었지만 getShapeInfo
함수에서 처리를 누락할 수 있습니다. 이를 switch
문을 사용하여 방지할 수 있습니다.
type Shape =
| { kind: 'circle', radius: number }
| { kind: 'rectangle', width: number; height: number }
| { kind: 'polygon' };
function getShapeInfo(shape: Shape) {
switch (shape.kind) {
case 'circle':
return `반지름 ${shape.radius}`;
case 'rectangle':
return `사이즈 ${shape.width}${shape.height}`;
default:
const exhaustiveCheck: never = shape;
return exhaustiveCheck;
}
}
이렇게 never
타입을 리턴하는 경우가 발생하면 컴파일 시점에 typescript에서 에러가 발생합니다!
결론적으로 switch문을 사용하면 모든 경우를 강제 검사할 수 있게됩니다.