【问题标题】:Multiple inheritance workarounds多重继承解决方法
【发布时间】:2023-04-08 20:43:01
【问题描述】:

我正在尝试发现一种将多个接口组合成一个抽象类的模式。目前我可以通过implements组合多个接口,但是一个接口不能声明一个构造函数。当我必须引入构造函数时,我不得不使用抽象类。当我使用抽象类时,我必须重新声明整个复合接口!我肯定错过了什么吗?

interface ILayerInfo {
    a: string;
}

interface ILayerStatic {
    b(): string;
}

class Layer implements ILayerInfo, ILayerStatic {
    constructor(info: ILayerInfo);
    a: string;
    b(): string;
}

回答:使用new

interface Layer extends ILayerInfo, ILayerStatic {
    new(info: ILayerInfo);
}

// usage: new Layer({ a: "" });

【问题讨论】:

    标签: abstract-class typescript multiple-inheritance


    【解决方案1】:

    在与实例成员相同的接口上声明构造函数并没有多大意义——如果你要动态传递一个类型以在构造函数中使用,那将是类的静态部分受限制的。你想要做的可能是这样的:

    interface Colorable {
        colorize(c: string): void;
    }
    
    interface Countable {
        count: number;
    }
    
    interface ColorCountable extends Colorable, Countable {
    }
    
    interface ColorCountableCreator {
        new(info: {color: string; count: number}): ColorCountable;
    }
    
    class ColorCounted implements ColorCountable {
        count: number;
        colorize(s: string) { }
        constructor(info: {color: string; count: number}) {
            // ...
        }
    }
    
    function makeThings(c: ColorCountableCreator) {
        var results: ColorCountable[];
        for(var i = 0; i < 10; i++) {
            results.push(new c({color: 'blue', count: i}));
        }
        return results;
    }
    
    var items = makeThings(ColorCounted);
    console.log(items[0].count);
    

    另见How does typescript interfaces with construct signatures work?

    【讨论】:

    • 我缺少的是界面上的“new”关键字!我根本不想上课。有了“新”,我可以坚持使用界面。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    相关资源
    最近更新 更多