type Circle = { kind: 'circle'; radius: number };
type Rect = { kind: 'rect'; width: number; height: number };
type Shape = Circle | Rect;
function isCircle(shape: Shape) {
return shape.kind === 'circle';
}
function isRect(shape: Shape) {
return shape.kind === 'rect';
}
const myShapes: Shape[] = getShapes();
// error because typescript doesn't know the filtering
// narrows typing
const circles: Circle[] = myShapes.filter(isCircle);
// you may be inclined to add an assertion:
// const circles = myShapes.filter(isCircle) as Circle[];
typescript는 필터링할때 타입을 자동으로 좁히지 못합니다.
function isCircle(shape: Shape): shape is Circle {
return shape.kind === 'circle';
}
function isRect(shape: Shape): shape is Rect {
return shape.kind === 'rect';
}
...
// now you get Circle[] type inferred correctly
const circles = myShapes.filter(isCircle);
참고: https://dev.to/zenstack/11-tips-that-help-you-become-a-better-typescript-programmer-4ca1?utm_source=Nomad+Academy&utm_campaign=b10d81b8b2-EMAIL_CAMPAIGN_2023_01_06&utm_medium=email&utm_term=0_4313d957c9-b10d81b8b2-49539437&mc_cid=b10d81b8b2&mc_eid=e598a309bd