【问题标题】:TypeScript - Can't set type of function to overloadTypeScript - 无法将函数类型设置为重载
【发布时间】:2020-12-11 14:14:45
【问题描述】:

我试图将函数的类型设置为定义为接口属性的重载类型,但函数参数却得到Binding element 'text' implicitly has an 'any' type.ts(7031)。重载的 args 类型都相同,所以我不确定为什么会出错。

interface Args {
  text: string
}

interface Utils {
  toUpperCase?(args: Args): string
  toUpperCase?(args: Args): any
}

export const toUpperCase: Utils['toUpperCase'] = ({ text }) => text.toUpperCase()

单独使用任一重载都可以正常工作,所以如果我删除其中一个(没关系),那么错误就消失了,例如

interface Utils {
  toUpperCase?(args: Args): string
  // toUpperCase?(args: Args): any
}

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    在函数参数中添加:Args 显式类型似乎可以消除编译器错误。

    interface Args {
      text: string
    }
    
    interface Utils {
      toUpperCase?(args: Args): string
      toUpperCase?(args: Args): any
    }
    
    export const toUpperCase: Utils['toUpperCase'] = ({ text }: Args) => text.toUpperCase()
    

    看起来没有或可能无法推断右边的函数在没有它的情况下满足Utils['toUpperCase'] 的签名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-23
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      相关资源
      最近更新 更多