gpt4 book ai didi

typescript - 从泛型类中的类型参数创建一个新对象

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:37 24 4
gpt4 key购买 nike

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

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;
}
}
}

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

最佳答案

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

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

看到这个问题: Generic Type Inference with Class Argument

关于typescript - 从泛型类中的类型参数创建一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com