typescript 多重继承解决方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17865620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:07:10  来源:igfitidea点击:

Multiple inheritance workarounds

abstract-classtypescriptmultiple-inheritance

提问by Corey Alix

I'm trying to discover a pattern for combining multiple interfaces into one abstract class. Presently I can combine multiple interfaces via implements, but an interface cannot declare a constructor. When I must introduce a constructor I'm forced to use an abstract class. When I use a abstract class I must re-declare the entire composite interface! Surely I'm missing something?

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

interface ILayerInfo {
    a: string;
}

interface ILayerStatic {
    b(): string;
}

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

ANSWER: Use new:

答案:使用new

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

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

回答by Ryan Cavanaugh

Declaring a constructor on the same interface as the instance members doesn't really make much sense -- if you're going to pass in a type dynamically to use in a constructor, it's the static side of the class that would be restricted. What you would want to do is probably something like this:

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

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);

See also How does typescript interfaces with construct signatures work?

另请参阅具有构造签名的打字稿接口如何工作?