noImplicitReturnType [Suggestion]
See original GitHub issueWe have noImplicitReturns
which is great and helps tick up silly mistakes but it woud great to have noImplicitReturnType
as well.
So what would noImplicitReturnType
do?
Currently we can write a function like so:
function life () {
return 42;
}
let x = life(); // Number
So all is great, TypeScript works out the return type nicely for us.
function life (x: boolean) {
if (x) {
return 'hi';
} else {
return 42;
}
}
let y = life(true); // Number / String
This is where things start to go a little crazy. TypeScript records y as of type number | string
which is of course acurate. But what if i wanted this function to only return strings?
We already have support for that with limited modifications
function life (x: boolean): string {
if (x) {
return 'hi';
} else {
return 42; // Type '42' is not assignable to type 'string'.
}
}
let y = life(true);
And as a result TypeScript nicly throws an error.
So my suggestion is that in much the same way as with noImplicitAny
and let
enforcing strict typeing an argument is added in the form of noImplicitReturnType
which for my first example (only a single return) wouldn’t have any effect but for the second would throw an error instead of typing the function as number | string
Issue Analytics
- State:
- Created 6 years ago
- Reactions:6
- Comments:8 (5 by maintainers)
Top GitHub Comments
I worry that new developers will enable this feature long before they fully understand the nature and expressive power of TypeScript’s type system.
More concretely I think that adopting this would very likely result in
any
There are already many misconceptions about TypeScript which have lead to poor coding practices that result in a failure to take advantage of the language.
Here is an unfortunately typical example from a Stack Overflow question:
We can all agree that such code is terrible, but why was it written that way?
I really want to stress that the above pattern is common.
I think adding this feature would be a serious mistake.
You might be interested in the
typedef
tslint rule.