【问题标题】:Overloading method throws Duplicate error in Typescript重载方法在 Typescript 中引发重复错误
【发布时间】:2019-11-06 13:06:36
【问题描述】:

我有下一段代码:

public async insert(data: iFlower | iFlower[]): Promise<iFlower> | Promise<iFlower[]> {
 await this.insert(data);
}

private async insert(data: iFlower): Promise<iFlower>{
 ....
 return data;
}

private async insert(data: iFlower[]): Promise<iFlower[]> {
 ....
 return data;
}

iFlower 是:

export interface iFlower {
   color: string;
   number: string;
}

我收到以下错误: The return type of an async function or method must be the global Promise&lt;T&gt; type. Duplicate function implementation. 'insert' is declared but its value is never read.

是不是因为iFlower是一个接口?

【问题讨论】:

    标签: typescript overloading


    【解决方案1】:

    当您在 typescript 中进行重载时,您唯一提供的就是类型的倍数。实际的实现只是一个函数。因此,您将为函数执行一系列类型,然后是一个与所有这些类型兼容的实现,如下所示:

    private async insert(data: iFlower): Promise<iFlower>;
    private async insert(data: iFlower[]): Promise<iFlower[]>;
    private async insert(data: iFower | iFlower[]): Promise<iFlower> | Promise<iFlower[]> {
      // Your code here. Maybe something like:
      if (Array.isArray(data)) {
        ... 
        return data;
      } else {
        ... 
        return data;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2018-02-19
      • 2015-07-23
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 2015-09-07
      相关资源
      最近更新 更多