简体   繁体   English

TypeScript - 无法将 function 的类型设置为过载

[英]TypeScript - Can't set type of function to overload

I am trying to set the type of a function to be an overload type that is defined as the property of an interface, but am getting Binding element 'text' implicitly has an 'any' type.ts(7031) for the function arguments. The overloads all have the same typing for the args so I'm not sure why it's erroring.我正在尝试将 function 的类型设置为定义为接口属性的重载类型,但我正在获取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()

It works fine with either overload individually, so if I remove one of them (doesn't matter which), then the error is gone, eg它可以很好地单独处理任何一个过载,所以如果我删除其中一个(无关紧要),那么错误就消失了,例如

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

Adding an :Args explicit typing to the function parameter seems to eliminate the compiler error.:Args显式类型添加到 function 参数似乎可以消除编译器错误。

interface Args {
  text: string
}

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

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

Looks like the inference isn't or maybe can't be made that the function on the right fulfils the signature of Utils['toUpperCase'] without it.看起来没有或可能无法推断出右边的 function 没有它就满足Utils['toUpperCase']的签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM