클래스로 런타임에도 타입 지정

nearworld·2023년 3월 6일
0

typescript

목록 보기
21/28
class Shape {
    width: number;
    height: number;
    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }
    static checkShape(shape: ShapeType) {
        if (shape instanceof Rectangle)
            return 'rectangle';
         else if (shape instanceof Square)
            return 'square';
        return 'no valid shape'
    }
}
type ShapeType = Rectangle | Shape;
class Square extends Shape {
}

class Rectangle extends Shape {
}

const square = new Square(10, 10);
const rect = new Rectangle(100, 100);

console.log(Shape.checkShape(rect));
// console.log(Shape.checkShape(square));
profile
깃허브: https://github.com/nearworld

0개의 댓글