从泛型类中的类型参数创建新对象

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


找不到符号'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;

        }

    }

}

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


慕哥9229398
浏览 982回答 3
3回答

芜湖不芜

因为已编译的JavaScript删除了所有类型信息,所以您不能使用它T来创建对象。您可以通过将类型传递给构造函数来以非泛型方式进行操作。class TestOne {&nbsp; &nbsp; hi() {&nbsp; &nbsp; &nbsp; &nbsp; alert('Hi');&nbsp; &nbsp; }}class TestTwo {&nbsp; &nbsp; constructor(private testType) {&nbsp; &nbsp; }&nbsp; &nbsp; getNew() {&nbsp; &nbsp; &nbsp; &nbsp; return new this.testType();&nbsp; &nbsp; }}var test = new TestTwo(TestOne);var example = test.getNew();example.hi();您可以使用泛型来扩展此示例以加强类型:class TestBase {&nbsp; &nbsp; hi() {&nbsp; &nbsp; &nbsp; &nbsp; alert('Hi from base');&nbsp; &nbsp; }}class TestSub extends TestBase {&nbsp; &nbsp; hi() {&nbsp; &nbsp; &nbsp; &nbsp; alert('Hi from sub');&nbsp; &nbsp; }}class TestTwo<T extends TestBase> {&nbsp; &nbsp; constructor(private testType: new () => T) {&nbsp; &nbsp; }&nbsp; &nbsp; getNew() : T {&nbsp; &nbsp; &nbsp; &nbsp; return new this.testType();&nbsp; &nbsp; }}//var test = new TestTwo<TestBase>(TestBase);var test = new TestTwo<TestSub>(TestSub);var example = test.getNew();example.hi();

慕哥6287543

要在通用代码中创建新对象,您需要通过其构造函数来引用类型。所以不用写这个:function activatorNotWorking<T extends IActivatable>(type: T): T {&nbsp; &nbsp; return new T(); // compile error could not find symbol T}您需要编写以下代码:function activator<T extends IActivatable>(type: { new(): T ;} ): T {&nbsp; &nbsp; return new type();}var classA: ClassA = activator(ClassA);

幕布斯6054654

所有类型信息都在JavaScript端被擦除,因此您不能像@Sohnee状态那样更新T,但是我更喜欢将类型化参数传递给构造函数:class A {}class B<T> {&nbsp; &nbsp; Prop: T;&nbsp; &nbsp; constructor(TCreator: { new (): T; }) {&nbsp; &nbsp; &nbsp; &nbsp; this.Prop = new TCreator();&nbsp; &nbsp; }}var test = new B<A>(A);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript