MST

星途 面试题库

面试题:TypeScript Mixin在复杂继承结构中的应用

假设有一个多层继承结构,最顶层是`Base`类,中间层有`Derived1`和`Derived2`类继承自`Base`,现在需要通过Mixin为`Derived1`和`Derived2`分别添加不同功能的方法,同时保证类型安全,简述实现步骤并编写相关TypeScript代码。
17.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 定义Mixin类,Mixin类通常是一个包含要添加功能方法的类,但不应该直接实例化,只是作为功能的集合。
    • 使用TypeScript的类型断言和类型约束来确保类型安全。
    • 将Mixin类的功能“混入”到目标类中。
  2. 相关TypeScript代码
// 定义顶层Base类
class Base {
    baseMethod() {
        console.log('This is a base method');
    }
}

// 定义第一个Mixin类
class Mixin1 {
    mixin1Method() {
        console.log('This is a method from Mixin1');
    }
}

// 定义第二个Mixin类
class Mixin2 {
    mixin2Method() {
        console.log('This is a method from Mixin2');
    }
}

// 将Mixin1混入Derived1
class Derived1 extends Base {
    constructor() {
        super();
        // 使用类型断言来确保类型安全
        Object.assign(this, new Mixin1());
    }
}

// 将Mixin2混入Derived2
class Derived2 extends Base {
    constructor() {
        super();
        // 使用类型断言来确保类型安全
        Object.assign(this, new Mixin2());
    }
}

// 测试代码
const derived1 = new Derived1();
derived1.baseMethod();
(derived1 as Mixin1).mixin1Method();

const derived2 = new Derived2();
derived2.baseMethod();
(derived2 as Mixin2).mixin2Method();