TypeScript中未检查“ void”返回类型–防止浮动承诺? [英] 'void' return type not checked in TypeScript – prevent floating promises?

查看:370
本文介绍了TypeScript中未检查“ void”返回类型–防止浮动承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript 3.9.7中运行,这与编译器无关:

Running in TypeScript 3.9.7, this does not concern the compiler:

const someFn: () => void = () => 123;

我发现了此答案,这说明这是设计使然。我得到了一些背后的理由(基本上,在将函数作为参数传递时,您应该能够忽略返回类型)。

I discovered this answer, which explains that this is by design. I somewhat get the reasoning behind it (basically, you should be able to ignore the return type when passing the function as an argument).

但是,关于诺言的故事却大不相同:

But the story becomes a different one looking at promises:

const someFn: () => void = () =>
  new Promise((resolve, reject) => reject(Error('onoez')));
someFn();

我正在用 eslint s <$ c $检查我的代码c> @ typescript-eslint / no-floating-promises 规则,以避免未处理的承诺被拒绝。在上面的脚本中,由于linter认为 someFn 不返回任何内容,因此不会警告我。

I am checking my code with eslints @typescript-eslint/no-floating-promises rule to avoid unhandled promise rejections. In the script above, since the linter thinks someFn does not return anything, it will not warn me.

我有这个吗?住在一起?如果函数接受()=> void 类型回调,我将异步函数传递给它,编译器将不会警告我,并且坏事将开始发生。我可以以某种方式避免这种情况吗?

Is this something I have to live with? If a function accepts a () => void type callback, and I pass it an async function, the compiler will not warn me and bad things will start to happen. Can I somehow avoid this?

推荐答案

void 的返回类型意味着无论它是什么,打字稿都不会让您使用返回值。但是请注意,这并不妨碍您返回某些东西。您不会改变这种行为。

A return type of void means typescript won't let you use the return value, whatever it is. But as you note, that doesn't prevent from returning something. You won't be changing that behaviour.

()=>无效意味着您不在乎返回值是什么,因为您不打算使用它。但是,在这种情况下,您确实会在意。

() => void means you don't care what the return value is, because you don't plan to use it. But, in this case you do care.

因此,您可以声明一个函数类型,该函数类型强制其不返回任何任何值。通过使用 undefined 的返回类型。

So you can declare a function type that enforces that it does not return any value by using a return type of undefined.

const someFn: () => undefined = () =>
  // Type 'Promise<unknown>' is not assignable to type 'undefined'.
  new Promise((resolve, reject) => reject(Error('onoez')));

这篇关于TypeScript中未检查“ void”返回类型–防止浮动承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆