Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

'void' return type not checked in TypeScript – prevent floating promises?

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();

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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')));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...