Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 通过接受构造函数中的基类型在运行时扩展类?_Typescript - Fatal编程技术网

Typescript 通过接受构造函数中的基类型在运行时扩展类?

Typescript 通过接受构造函数中的基类型在运行时扩展类?,typescript,Typescript,我想知道如何在运行时“增长”一个类。我不确定我想要实现的目标的正确术语是什么,但我希望我的代码示例能够清楚地说明这一点 class foo { protected message: string; public SetMessage(message: string) { this.message = message; } } class bar extends foo { constructor(baseClass: foo) {

我想知道如何在运行时“增长”一个类。我不确定我想要实现的目标的正确术语是什么,但我希望我的代码示例能够清楚地说明这一点

class foo {
    protected message: string;

    public SetMessage(message: string) {
        this.message = message;
    }
}

class bar extends foo
{
    constructor(baseClass: foo)
    {
        // Not possible
        this = baseClass as bar;
        alert(this.message);
    }
}

let baseClass = new foo();
baseClass.SetMessage("Hello World");
let extendedClass = new bar(baseClass);

现在还不完全清楚您为什么要这样做,如果您想在新实例中拥有现有实例的属性,那么您可以:

class bar extends foo {
    constructor(base: foo) {
        super();
        Object.assign(this, base);
    }
}