为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥9229398 2019-11-12 09:42:08
我正在尝试在我的通用类中创建一个类型参数的新对象。在我的课程中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;        }    }}我可以从通用类型创建对象吗?
查看完整描述

3 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

因为已编译的JavaScript删除了所有类型信息,所以您不能使用它T来创建对象。


您可以通过将类型传递给构造函数来以非泛型方式进行操作。


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();

您可以使用泛型来扩展此示例以加强类型:


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();


查看完整回答
反对 回复 2019-11-12
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

要在通用代码中创建新对象,您需要通过其构造函数来引用类型。所以不用写这个:


function activatorNotWorking<T extends IActivatable>(type: T): T {

    return new T(); // compile error could not find symbol T

}

您需要编写以下代码:


function activator<T extends IActivatable>(type: { new(): T ;} ): T {

    return new type();

}


var classA: ClassA = activator(ClassA);


查看完整回答
反对 回复 2019-11-12
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

所有类型信息都在JavaScript端被擦除,因此您不能像@Sohnee状态那样更新T,但是我更喜欢将类型化参数传递给构造函数:


class A {

}


class B<T> {

    Prop: T;

    constructor(TCreator: { new (): T; }) {

        this.Prop = new TCreator();

    }

}


var test = new B<A>(A);


查看完整回答
反对 回复 2019-11-12
  • 3 回答
  • 0 关注
  • 979 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信