键入函数构造函数

时间:2016-01-14 09:24:32

标签: typescript

我有课:

class Parent {
    method(): string {
        return "result";
    }
}

我需要这个班的孩子。在TypeScript中,它很简单 class Child extends Parent 。但由于某些原因,我需要使用“旧”方法:

function Fake(): void {}
Fake.prototype = Parent.prototype;
function Child(): void {
}
Child.prototype = new Fake();

我可以以某种方式向编译器明确说明Child扩展了Parent吗?

尝试失败:

const Child: typeof Parent = <typeof Parent>function Child(): void {
    // ...
};

解释我的奇怪愿望

  1. 我需要一个函数(取决于参数)创建扩展不同父类的类。
  2. 例如,我想创建从Error或TypeError继承的异常类。

    1. 此函数将用于纯JavaScript(不在TypeScript中),并且不使用extends。

2 个答案:

答案 0 :(得分:1)

在这种情况下,类扩展可能不是首选方法。

TypeScript确实支持mixins。

它们允许您通过组合其他类的部分来创建类。

它看起来像这样:

class ErrorKindA {
    errorMessage: string;
    getError(): string {
        return this.errorMessage;
    }
}

class ErrorKindB  {
    information: string;
    getInformation(): string {
        return this.information;
    }

}

class Child implements ErrorKindA, ErrorKindB {
    constructor() {

        var fromA = this.getError();
        var fromB = this.getInformation();
    }
    otherThing: string= "abc";
    getThing(): string {
        return this.otherThing;
    }
    // A
    errorMessage: string ="errror ";
    getError:()=> string;

    // B
    information: string = "info stuff";
    getInformation: () => string;
}




applyMixins(Child, [ErrorKindA, ErrorKindB]);




enum Kind {
    A, B
}

function createChild(kind: Kind){
    if(kind == Kind.A) {
        applyMixins(Child, [ErrorKindA]);
        return Child;
    } else {
        applyMixins(Child, [ErrorKindB]);
        return Child;
    }

} 

////////////////////////////////////////
// In your runtime library somewhere
////////////////////////////////////////

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        })
    });
}

您可以看到此here的实际示例。

您可以在TypeScript here中找到有关mixin的更多信息。

答案 1 :(得分:1)

您必须省略一些细节,因为以下代码有效:

class Parent {
    method(): string {
        console.log("test");
        return "result";
    }
}

class Child extends Parent {    
}

let c = new Child();
c.method();

Playground

您可以在浏览器的控制台中运行已编译的代码