TypeScript:将泛型作为参数传递给泛型类 [英] TypeScript: pass generic type as parameter in generic class
问题描述
TypeScript: 我在DataProvider类中有一个方法,其中有一个方法getTableData:
TypeScript: I have a method in the DataProvider class with a method getTableData:
public static getTableData<T extends DataObject>(type: { new(): T}): Array<T> { ... }
这在我编写代码时非常有效:
this works perfectly when I code:
let speakers = DataProvider.getTableData(Speaker); // where Speaker is a class
现在我要从通用类中调用它:
now I want to call this from a generic Class:
export class ViewModelBase<T extends DataObject> {
public getData(): Array<T> {
return <T[]> DataProvider.getTableData(T);
}
}
现在我收到传递给getTableData的T参数的找不到名称'T'错误.应该如何调用getTableData?
Now I get a Cannot find name 'T' error for the T parameter I pass to getTableData. How should getTableData be called?
更新: 在@Paleo的帮助下,我想到了这一点:
update: With the help of @Paleo I came up this:
export class ViewModelBase<T extends DataObject> {
constructor(private dataObjectClass: { new(): T}){}
public getTableData(): Array<T> {
return <T[]> DataProvider.getTableData<T>(this.dataObjectClass);
}
}
问题是,尽管我已经告诉过:
class SpeakerViewModel extends ViewModelBase<Speaker> { ... }
我希望它成为Speaker
的ViewModel,我仍然像SpeakerViewModel
那样实例化:
the thing is that although I have already told in:
class SpeakerViewModel extends ViewModelBase<Speaker> { ... }
that I want it to be a ViewModel for Speaker
I still have the instantiate the SpeakerViewModel
like:
let vm = new SpeakerViewModel(Speaker);
尽管我已经告诉过所有有关Speaker
的内容.我想我还是不太了解.
although I have already told it is all about Speaker
. I guess I still don't fully understand this.
推荐答案
泛型只是元数据.调用函数时,不能将它们用作参数.也许您需要这样的东西:
Generics are just metadata. They cannot be used as parameters when calling a function. Maybe you need something like this:
export class ViewModelBase<T extends DataObject> {
constructor(private Cl: {new(): T}) {
}
public getData(): Array<T> {
return DataProvider.getTableData<T>(this.Cl);
}
}
这篇关于TypeScript:将泛型作为参数传递给泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!