我正在尝试以标准方式创建通用方法(用于调用后端)。
这是问题所在,我输入了一个特殊的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
中看到,现在显示为typ
:Object
。
输入typ
方法后,他正在丢失Generic_
。参见here。
我在这里可以做什么?
typeof arg
=>“对象”
答案 0 :(得分: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中使用泛型函数的示例。
希望它能帮助^^