泛型类中数组属性的实例?

马诺兹

我有一个具有 2 个属性的通用打字稿类 -

export class WrapperModel<T>{
    constructor(private testType: new () => T) {
        this.getNew();
    }

    getNew(): T {
        return new this.testType();
    }
    public Entity: T;
    public ShowLoading: boolean;
}

然后按如下方式使用它 -

this.userModel = new WrapperModel<UserProfileModel>(UserProfileModel);

我假设它正在UserProfileModel其构造函数中创建一个类型的实例

但是当我尝试使用 Array 类型属性时,它失败了。就像我做的那样 -

this.userModel = new WrapperModel<Array<UserProfileModel>>(Array<UserProfileModel>);

我在上述情况下得到的错误 -

在此处输入图片说明

是不是我不能在泛型或其他东西中创建 Array 属性的实例。我的需要很简单;我想Array在 Generic 类中创建属性的实例

提香·切尔尼科娃-德拉戈米尔

问题是在运行时泛型被删除了,所以Array<UserProfileModel>不是真正的构造函数,Array是构造函数,所以你可以写:

var userModel = new WrapperModel<Array<UserProfileModel>>(Array);

这适用于任何泛型类型,而不仅仅是数组:

class Generic<T> {  }
var other = new WrapperModel<Generic<UserProfileModel>>(Generic);

通常对于泛型类,似乎没有一种方法可以获取特定类型实例化的构造函数,只有泛型构造函数:

// Valid, new get a generic constrcutor
var genericCtor: new <T>() => Generic<T> = Generic;

// Not valid,  Generic<UserProfileModel> is not callable
var genericCtor: new () => Generic<UserProfileModel> = Generic<UserProfileModel>;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章