如何将接口作为参数传递并在 TypeScript 中获得匿名回调?

How to pass interface as an argument and get anonymous call back in TypeScript?

这是代码,我正在努力实现:

this._customHttp.httpPostService('app/fetchGridDetails',this.req,new  
  InterfaceName() {
         onEvent(str :string) {
            console.log(str);
         }
    });

如果它是一个接口而不是 class,你就不会 new 了。您可以只创建一个内联实现接口的对象:

this._customHttp.httpPostService('app/fetchGridDetails', this.req,
    <InterfaceName>{
        onEvent(str: string) {
            console.log(str);
        }
    });

您可能甚至不需要显式地写接口名称。如果对象具有 httpPostService 所期望的正确方法,TypeScript 应该编译它:

this._customHttp.httpPostService('app/fetchGridDetails', this.req,
    {
        onEvent(str: string) {
            console.log(str);
        }
    });