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

前端 未结 1 536
心在旅途
心在旅途 2020-12-22 04:13

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

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

I discovered this answer, which

相关标签:
1条回答
  • 2020-12-22 04:36

    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')));
    
    0 讨论(0)
提交回复
热议问题