DEV Community

Yann
Yann

Posted on

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

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 !

Top comments (7)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

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.

Collapse
 
yanns1 profile image
Yann

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 !

Collapse
 
devhammed profile image
Hammed Oyedele • Edited

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.

Collapse
 
brandinchiu profile image
Brandin Chiu

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.

Collapse
 
yanns1 profile image
Yann

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

Collapse
 
subztep profile image
Andras Serfozo

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

Collapse
 
yanns1 profile image
Yann

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.