宽松类型,通用方法

问题描述 投票:0回答:1

我正在尝试以标准方式创建通用方法(用于调用后端)。

这里是问题,我传入了一个特殊的type(此处为Recipe):

let a = this._adminService.Generic_(this.UI_Recipes[0], ECRUD.Create, EProductType.Recipe);

而且我想在另一侧读取该类名(type):

Generic_<T>(arg: T, method: ECRUD, producttype: EProductType): T {
//...
call = this.baseUrl + product + arg.constructor.name; // => "Object"
//...

我在调试器arg中看到,现在为typObject。输入typ方法后,他正在失去Generic_。参见here

我在这里可以做什么?

typeof arg =>“对象”

angular typescript
1个回答
0
投票

请求的示例:

class ScriptPosition{
  line:number;
  path:string;
  time:string;

  constructor(time:string, line:number, path?:string){
    this.time = time;
    this.line = line;
    this.path = path || null;
  }
}

class _Command extends ScriptPosition{

  constructor(time:string, line:number, path?:string){
    super(time, line, path);
  }
}

class _Step extends ScriptPosition{

  constructor(time:string, line:number, path?:string){
    super(time, line, path);
  }
} //and so on
@Component({...})
export class ScriptLogComponent implements OnInit, OnDestroy {
   ...
   ngOnInit(){
     this.setLogPath<_Command>(_Command);
     setTimeout(() => {
       this.setLogPath<_Step>(_Step, 1550);
     }, 10000);
   }

   setLogPath<T extends ScriptPosition>(constructor:{new (...args: any[]):T}, scriptPosition?:T){
     ///Do something with scriptPosition or call another function like this:
     scriptPosition = scriptPosition || this._getScriptPositionTypeFromLineIndex<T>(this.actualLineIndex, constructor);
   }

   private _getScriptPositionTypeFromLineIndex<T extends ScriptPosition>(index:number, constructor:{new (...args: any[]):T}):T{...}
   ...
}

这只是有关如何在TypeScript中使用泛型函数的示例。

希望有帮助^^

© www.soinside.com 2019 - 2024. All rights reserved.