【问题标题】:Missing return type on function in Jest / eslintJest / eslint中的函数缺少返回类型
【发布时间】:2020-10-12 08:31:45
【问题描述】:

我的项目中有这个笑话

const action = async () => {
                await hotelService.getByIdAsync(Identifier);
};

await expect(action()).rejects.toThrowError(FunctionalError);

但我有这个 eslint 错误

 92:28  error  Missing return type on function  @typescript-eslint/explicit-function-return-type

【问题讨论】:

  • 动作函数没有返回任何东西,因此你期望它抛出错误。
  • ESLint 消息中有什么不清楚的地方?您是否阅读了规则的指南?请注意,您可能希望对测试使用不同的、更宽松的 linting 规则。

标签: javascript node.js typescript async-await jestjs


【解决方案1】:

您需要明确指定函数的返回类型。因为函数是async,所以它返回一个包裹hotelService.getByIdAsync(Identifier)返回的数据的Promise

const action = async (): Promise</*type of data wrapped in promise*/> => {
   return await hotelService.getByIdAsync(Identifier);
};

【讨论】:

  • 我收到错误“TS2355:声明类型既不是'void'也不是'any'的函数必须返回一个值”
  • await之前添加一个return关键字
  • 这会改变函数的行为 - 它没有在之前返回任何值:)
  • @eol async 函数总是返回一个Promise,无论你是否编写return 语句
  • 当然,但在这种情况下它是一个无效的 Promise。
【解决方案2】:

action 函数未指定返回类型,因此出现错误。为了消除 linting 错误,您需要将返回类型设置为 Promise&lt;void&gt;,因为该函数是异步的,因此只返回一个没有实际值的已解决承诺:

const action = async () : Promise<void> => {
    await hotelService.getByIdAsync(Identifier);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2021-06-27
    • 2019-07-15
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多