首页 > 解决方案 > 未实例化类的数组的打字稿数据类型

问题描述

我想在 Typescript 类中实现“特征”(如 PHP)功能。我认为下面的代码可以工作,但事实并非如此。我不知道为什么,因为这对我来说很有意义。

interface Trait {
    register: (Model: BaseModel, option?: object) => void
}

interface IPrototype {
    prototype: any;
}

class Tenable implements Trait {
    register(Entity: BaseModel & IPrototype, option = {}) {
        Entity.prototype.hello = function () {
            console.log('Hello World from Tenable!');
        }
    }
}

class BaseModel { 
  protected traits: Trait[] = [];
}

class A extends BaseModel {
  protected traits = [Tenable];
}

如果您在 Typescript Playgound 中运行此代码,您会看到错误。打字稿游乐场

标签: typescript

解决方案


这意味着一个对象数组Trait

protected traits: Trait[] = [];

Trait但是在这里,您使用对象构造函数创建了一个数组。

protected traits = [Tenable];

要获得构造此类对象的构造函数列表,您需要更改特征类型。

protected traits: (new () => Trait)[] = [];

推荐阅读