type
을 설정해야 좋다.타입 추론
이 되는데, 타입 추론을 쓰는게 더 좋을지 type
설정해서 쓰는게 좋을지 잘 모르겠음"noImplicitAny": true
const add = (a, b) => a + b // 오류
const add = (a: number, b: number) => a + b // 정상
interface Square {
width: number;
}
interface Rectangle extends Square {
height: number;
}
type Shape = Square | Rectangle;
function calculateArea(shape: Shape) {
if (shape instanceof Rectangle) { // 'Rectangle' 은 형식만 참조, 여기서는 값으로만 사용 되고 있습니다
return shape.width * shape.height; // 'Shape' 형식에 'height' 속성이 없습니다
}
return shape.width * shape.width;
}
type guard
interface Square {
kind: 'square';
width: number;
}
interface Rectangle extends Square {
kind: 'rectangle';
height: number;
}
type Shape = Square | Rectangle;
function calculateArea(shape: Shape) {
if (shape.kind === 'rectangle') {
return shape.width * shape.height;
}
return shape.width * shape.width;
}