Back when I was just starting with TypeScript, I used to neglect the value of declaring an explicit return type for my functions. Why bother specifying it when there is type inference and IntelliSense, right? Well, I was very wrong.
Turns out that its main benefit is actually not to whomever might call my function, but rather to whomever might edit my function in the future. Here's why...
Imagine I have this function:
function getAge(person: Person) {
return calculateAge(person.birthdate);
}
This is all good, as obviously it returns a number
, and IntelliSense tells me that, too. But then later on, someone edits my function to add a guard condition as follows:
function getAge(person: Person) {
if (person.birthdate === undefined) return null;
return calculateAge(person.birthdate);
}
This won't trigger a TS error at this function, but now the inferred return type has become number | null
, which is clearly different from the original intention. Now we have introduced, possibly unintentionally, a breaking change.
Now imagine if I have specified a return type in the first place, as follows:
function getAge(person: Person): number {
// . . .
}
then my team mate would have known from the start what can and can't be changed in the implementation without making a breaking change.
Top comments (5)
Agree, setting up the return type prevents from stupid mistakes, and allows to focus on results, and not on endless checks. One thing I'd like to add here, you have to decide how fragile your code should be there. I mean, try to answer to the question - "what will happen if I return null here and not a number?". As for me, for some cases I'd like to raise an exception, rather than returning null.
I don't know in TypeScript, but in Kotlin that also makes the compiler and IDE integration faster because he has less type inference magic to do. Also being explicit is the default.
There are a couple of scenarios that may be subject to debate whether adding explicit types is necessary:
JSX.Element
orReactElement
.void
. One can argue that a void function (imperative/procedural) is semantically different enough from a function that does return a value, therefore a different signature (no return type) could be justified.Some of us might prefer consistency in using explicit return types across the entire codebase. But some may find that, in the above scenarios, explicit return types are just added noise. Which camp are you guys in?
Too bad you can't specify the return type in JS.
You can still annotate using JSDoc though. π