Skip to content
loading...

Should we explicitly type the output of all functions (TypeScript) ?

yanns1 profile image Yann twitter logo github logo ・1 min read

I'm starting to learn TypeScript and I'm frustrated about if I should type functions output or not.

In one hand, I would like to be explicit and consistent in my code, which invite me to explicitly type the output.

But in the other hand there are type inferences and I feel that adding the output type can become verbose and thus, more difficult to read.
Finally (I'm not sure about this), I think that I've read in the doc that type inferences may fail when the type is complex. This last point is in favor of explicit output typing.

I wondered what our your thoughts on this, experienced TS developers, so share your opinions !

twitter logo DISCUSS (7)
Discussion
markdown guide
 

I'd suggest yes whenever possible. Anyone coming from a strongly-typed language will understand immediately what the extra code is doing, so I wouldn't worry too much about that.

The major benefit besides is not for us, but for the language itself, especially when you start working with more objects, as it will help your application be explicit while it passes objects and models around.

It also makes it easier to find type errors before runtime.

 

Yes, I've a tendency to think that's better to explicitly type the output.
Thanks !

 

I wouldn't. But if I consider doing, I would also consider writing TSDoc.

Actually, if I fallback to JavaScript, I almost always write JSDoc.

As for Type-checking, I only care about IDE. But for runtime, I would perhaps use runtypes or zod. TypeScript's typing is not to be trusted.

 

Interesting, I would have not imagine that TS was not perfectly type safe for runtime but that's true indeed, because it compiles to JS anyway.
Thanks for sharing these tools, I'll check out !

 

There is a new Type-checker that does just that for both development and runtime, check out Hegel and the best thing is you already knows it if you work with TypeScript or Flow and also with better type inference.

 

I don't, I write the minimum required type definitions and let VSCode do its job.

 

Sure, in fact, I think I'll go on this way. I talked with a mod on Discord that pointed out that the compiler is usually right. So if there's a problem it must be because of me.

Classic DEV Post from May 3

Solutions to Replace the 12-Column Grid

This is the eighth post in a series examining modern CSS solutions to problems I've been solving ove...

Yann profile image