Today I learned
Don't use return types in TypeScript
Every week or so a new hot topic gets discussed eagerly in the web development community. This week it was about the necessity of return types in TypeScript.
A few years ago, when I learned TypeScript, my colleagues taught me that return are absolutely necessary. I thought it was a no-brainer to define them. I felt good writing a function and then specifically add the return type.
But as you might have already guessed, I got convinced otherwise last week. To be clear, there seems to be no absolut consensus about this topic. But I decided that return types in TypeScript are not necessary and I won't define them anymore. I'll tell you why.
In TypeScript there are two ways to deal with return types. You can define them explicitely or you can let TypeScript infer them.
After listening to all the arguments about the necessity of return types, I came to a conclusion.
For most of the code I write, I don't need return types. Because if I define return types I just tell TypeScript what it already knows.
But as soon as a function I write is more complex, like containing a switch or an if statement I will define the return type.
As I already mentioned there is no right or wrong here, it just seems to be a preference. My preference is infer return types whenever possible, define return types only when TypeScript can't infer them properly.
I hope you enjoyed this post and learned something new. If you have any questions, feel free to reach out to me on Twitter ↗ or via Email ↗.
If you want to support me, you can buy me a coffee. I would be very happy about it!☕️ Buy me a coffee ☕️
I wish you a wonderful day! Marco