从泛型类中的类型参数创建一个新对象 [英] Create a new object from type parameter in generic class

查看:42
本文介绍了从泛型类中的类型参数创建一个新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的泛型类中创建一个类型参数的新对象.在我的类 View 中,我有 2 个泛型类型的对象列表作为类型参数传递,但是当我尝试制作 new TGridView() 时,TypeScript 说:

I'm trying to create a new object of a type parameter in my generic class. In my class View, I have 2 lists of objects of generic type passed as type parameters, but when I try to make new TGridView(), TypeScript says:

找不到符号'TGridView

Could not find symbol 'TGridView

这是代码:

module AppFW {
    // Represents a view
    export class View<TFormView extends FormView, TGridView extends GridView> {
        // The list of forms 
        public Forms: { [idForm: string]: TFormView; } = {};

        // The list of grids
        public Grids: { [idForm: string]: TGridView; } = {};

        public AddForm(formElement: HTMLFormElement, dataModel: any, submitFunction?: (e: SubmitFormViewEvent) => boolean): FormView {
            var newForm: TFormView = new TFormView(formElement, dataModel, submitFunction);
            this.Forms[formElement.id] = newForm;
            return newForm;
        }

        public AddGrid(element: HTMLDivElement, gridOptions: any): GridView {
            var newGrid: TGridView = new TGridView(element, gridOptions);
            this.Grids[element.id] = newGrid;
            return newGrid;
        }
    }
}

我可以从泛型类型创建对象吗?

Can I create objects from a generic type?

推荐答案

因为编译后的 JavaScript 已经删除了所有的类型信息,所以你不能使用 T 来新建一个对象.

Because the compiled JavaScript has all the type information erased, you can't use T to new up an object.

您可以通过将类型传递给构造函数来以非通用方式执行此操作.

You can do this in a non-generic way by passing the type into the constructor.

class TestOne {
    hi() {
        alert('Hi');
    }
}

class TestTwo {
    constructor(private testType) {

    }
    getNew() {
        return new this.testType();
    }
}

var test = new TestTwo(TestOne);

var example = test.getNew();
example.hi();

您可以使用泛型扩展此示例以收紧类型:

You could extend this example using generics to tighten up the types:

class TestBase {
    hi() {
        alert('Hi from base');
    }
}

class TestSub extends TestBase {
    hi() {
        alert('Hi from sub');
    }
}

class TestTwo<T extends TestBase> {
    constructor(private testType: new () => T) {
    }

    getNew() : T {
        return new this.testType();
    }
}

//var test = new TestTwo<TestBase>(TestBase);
var test = new TestTwo<TestSub>(TestSub);

var example = test.getNew();
example.hi();

这篇关于从泛型类中的类型参数创建一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆