如何在Typescript中定义类数组(非实例)

时间:2018-04-24 05:11:02

标签: typescript

我正在尝试使用Typescript中的一些语言结构。我希望创建一个类数组,稍后实例化类。 如果我在Typescript Playground上尝试它,我似乎编译并运行的代码,但它确实在typescript框中给出了错误:Argument of type 'typeof Greeter' is not assignable to parameter of type 'BaseGreeter'.

我想这是因为数组定义需要扩展BaseGreeter的类的实例,而不是扩展它的类本身。那是对的吗?如果是这种情况,我如何定义扩展BaseGreeter的类数组?

这是代码:

class BaseGreeter {
    greeting: string;
    greeting_start: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return this.greeting_start + ", " + this.greeting;
    }
}

class Greeter extends BaseGreeter{

    constructor(message: string) {
        super(message);
        this.greeting_start = "Hello";
    }
}

class Greeter2 extends BaseGreeter {
    constructor(message: string) {
        super(message);
        this.greeting_start = "Bye";
    }
}

class Greeter3 extends BaseGreeter {
    constructor(message: string) {
        super(message);
        this.greeting_start = "Adieu";
    }
}


function getGreeters() :[string, BaseGreeter[]]{
    let greeters = new Array<BaseGreeter>();
    greeters.push(Greeter);
    greeters.push(Greeter2);
    greeters.push(Greeter3);
    return ["test", greeters];
}

let foo = {};
let retval = getGreeters();
alert(retval[0]);
foo['greeters'] = retval[1];
var i = 0;

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    let greeter = new foo['greeters'][i]("cruel world");
    alert(greeter.greet());
    i = i + 1;
}

document.body.appendChild(button);

1 个答案:

答案 0 :(得分:4)

BaseGreeter类型表示值符合BaseGreeter接口,是BaseGreeter类的实例。指定BaseGreeter构造函数的类型为typeof BaseGreeter

function getGreeters(): [string, typeof BaseGreeter[]]{
    let greeters = new Array<typeof BaseGreeter>();
    greeters.push(Greeter);
    greeters.push(Greeter2);
    greeters.push(Greeter3);
    return ["test", greeters];
}