简体   繁体   English

重载的打字稿功能参数不适用于async关键字

[英]Overloaded typescript function parameter does not work with async keyword

I'm working on a larger project type definition file. 我正在处理更大的项目类型定义文件。 I have simplified the code into an isolated example: 我已将代码简化为一个孤立的示例:

Module definition fdts 模块定义fdts

export type myFunction = ((r: string) => Promise<any>) // async def
  | ((r: string, done: (err: Error | null, b?: any) => void) => void) //callback def

export interface addFunc {
  (c: string, f: myFunction): void
}

export interface FI {
  addFunc: addFunc
}

export default function f(): FI

Module implementation f.js 模块实现f.js

function f () {
  return {
    addFunc: (c, p) => {
      this[c] = p
      return this
    }
  }
}

module.exports = f

Module utilization index.ts 模块利用率指数

import f from './f'

f().addFunc('x', (r, d) => { // Compiles as expected
  d(null)
})

f().addFunc('x', async (r) => { // Error ts(7006) Parameter 'r' implicitly has an 'any' type.
  return null
})

Can you please explain why this error is happening and how I could fix it? 您能否解释为什么会发生此错误,以及如何解决? I believe the issue is in the type definition. 我认为问题出在类型定义中。

Please do not comment on the implementation itself; 请不要对实现本身发表评论; this is an extremely stripped down and isolated piece of a large API. 这是大型API的精简和隔离部分。

Thank you for the help! 感谢您的帮助!

You need to change it to 您需要将其更改为

f().addFunc('x', async (r: string) => {
  return null
})

Without adding : string , your function is really a (r: any) => Promise<null> , which is not assignable to the type myFunction . 如果不添加: string ,则您的函数实际上是(r: any) => Promise<null> ,它不能分配给myFunction类型。

The first case in your example compiles because TypeScript is able to infer the types of r and d by the fact that there're two parameters, which makes it impossible to assign to the first case in the union definition of myFunction . 您的示例中的第一种情况之所以编译,是因为TypeScript可以通过存在两个参数的事实来推断rd的类型,这使得无法在myFunction的并集定义中分配给第一种情况。 But when a function has only one parameter, it could be assigned to a type that has one or more parameters, so TypeScript cannot automatically infer the type of r . 但是,当一个函数只有一个参数时,可以将其分配给具有一个或多个参数的类型,因此TypeScript无法自动推断r的类型。

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

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