我正在尝试为从服务器获取响应的代理服务创建一个泛型类。当我继续实现这个类时,我遇到了一个问题,调用泛型类中的方法。如何从泛型类型中声明的in (Item)中调用静态方法?
export class CollectionResult<T> implements ICollectionResult<T> {
items: Array<T>;
constructor(data?: T) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
Object.assign(this, data);
this.items = [];
for (let item of data.items) {
this.items.push(T//NOTE: Error here//.fromJS(item));
}
}
}
fromJS(data: any): CollectionResult<T> {
let result = new CollectionResult<T>();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
Object.assign(data, this);
if (this.items && this.items.constructor === Array) {
data["items"] = [];
for (let item of this.items) {
data["items"].push(item);
}
}
return data;
}
}
export interface ICollectionResult<T> {
items: Array<T>;
}//传入CollectionResult的泛型类
export class ProgramDto implements
IProgramDto {
year: number;
month: number;
accounts: number;
constructor(data?: ProgramDto) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
Object.assign(this, data);
}
}
static fromJS(data: any): ProgramDto {
let result = new ProgramDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
Object.assign(data, this);
return data;
}
}
export interface IProgramDto {
year: number;
month: number;
accounts: number;
}//代理方法中的用法
Get(): Observable<CollectionResult<ProgramDto >> {
let url = `${this.baseUrl}/Api/Controller/Method`;
url = url.replace(/[?&]$/, "");
let options = this.getOptions();
return this.sendRequestWithResponse(url, options, CollectionResult<ProgramDto>.fromJS, new CollectionResult<ProgramDto>());
}发布于 2019-05-27 21:49:55
不能访问泛型类型参数的成员。类型参数在编译过程中被擦除,因此除了类型检查之外,您不能依赖它们进行任何其他操作。
您可以将类作为参数传入,并将其约束为具有fromJs方法:
type CollectionResultDataClass<T> = {
new(...a: any[]): T
fromJs(o: any): T
}
export class CollectionResult<T> implements ICollectionResult<T> {
items: Array<T>;
constructor(private cls: CollectionResultDataClass<T>, data?: T) {
// ...
}
init(data?: any) {
if (data) {
Object.assign(this, data);
this.items = [];
for (let item of data.items) {
this.items.push(this.cls.fromJs(item));
}
}
}
fromJS(data: any): CollectionResult<T> {
let result = new CollectionResult<T>(this.cls);
result.init(data);
return result;
}
toJSON(data?: any) {
//..
}
}
//Usage
class MyDataClass {
static fromJs(o: any) {
return Object.assign(new MyDataClass(), o);
}
}
new CollectionResult(MyDataClass, new MyDataClass());https://stackoverflow.com/questions/56327217
复制相似问题