MST

星途 面试题库

面试题:TypeScript受限多态在复杂类型系统中的深度应用

考虑一个复杂的场景,你正在开发一个图形渲染库。有各种图形形状类,如 `Circle`、`Rectangle` 等,它们都继承自一个抽象基类 `Shape`。现在你要创建一个 `Renderer` 类,它有一个泛型方法 `render`,这个方法能够接收任何 `Shape` 的子类型并进行渲染。但要求在渲染 `Circle` 时调用 `drawCircle` 方法,渲染 `Rectangle` 时调用 `drawRectangle` 方法。请用TypeScript实现这个 `Renderer` 类,充分利用受限多态和类型守卫等特性来确保类型安全和正确的行为,并阐述在这个复杂场景中受限多态是如何解决类型适配和复用问题的。
28.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
abstract class Shape {}

class Circle extends Shape {
    drawCircle() {
        console.log('Drawing a circle');
    }
}

class Rectangle extends Shape {
    drawRectangle() {
        console.log('Drawing a rectangle');
    }
}

class Renderer {
    render<T extends Shape>(shape: T) {
        if (shape instanceof Circle) {
            (shape as Circle).drawCircle();
        } else if (shape instanceof Rectangle) {
            (shape as Rectangle).drawRectangle();
        }
    }
}

受限多态在该场景中的作用

  1. 类型适配render 方法使用了泛型 T 并约束 TShape 的子类型(T extends Shape)。这使得 render 方法能够接收任何 Shape 的子类型,实现了对不同具体形状类型的适配。不必为每个具体形状类型都创建单独的渲染方法,增强了代码的灵活性。
  2. 复用:通过在 Renderer 类中定义一个通用的 render 方法,利用受限多态,可以复用该方法来处理所有 Shape 子类型的渲染逻辑。同时,通过类型守卫(instanceof)来判断具体类型,执行相应的特定渲染方法,既保证了代码复用,又保证了类型安全。