DEV Community

Cover image for Avoid using () => void in 2023
Shamil
Shamil

Posted on

Avoid using () => void in 2023

Hey, all! We all use () => void in typescript when we want to declare a function without arguments.

But do you know that this declaration can lead to bugs on runtime?

Let's consider the next example:

const verify = (address?: string) => address?.toLowerCase()
const verifyEmpty: () => void = verify
const onClick: (event: object) => void = verifyEmpty

onClick({ this: 'is not a string'})
Enter fullscreen mode Exit fullscreen mode

In the example above we assign verify function with optional argument to the function without arguments. And then reassign verifyEmpty to onClick.

But verify and onClick functions have different signatures of arguments: verify accepts a string, while onClick an object.

Does typescript allow this assignment through the third function verifyEmpty without arguments?

Yes! And on runtime we'll get the error:
address.toLowerCase is not a function.

Check it out on playground

So, how can we avoid that? How can we explicitly say, that function should have zero arguments?

The solution is pretty simple.

Let's just replace () => void with (...args: undefined[]) => void;:

const verify = (address?: string) => address?.toLowerCase()
const verifyEmpty: (...args: undefined[]) => void = verify
const onClick: (event: object) => void = verifyEmpty

onClick({ this: 'is not a string'})
Enter fullscreen mode Exit fullscreen mode

Now, the typescript tells us that verifyEmpty can't be assigned to onClick function: playground. The code won't compile and you won't see annoying bug on runtime.

Thanks for reading, hope it will help someone!

Happy coding and stay safe!

Top comments (1)

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!