Why explicit return type is a good thing
Arnel Enero
Posted on September 6, 2022
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.
Posted on September 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 25, 2024