Reputation: 3506
If I have the following basic function typescript
can infer the return type automatically.
function myFunction(x: number, y: number) {
return x * y;
}
Is it only useful to declare return types if typescript
cannot infer the return type because some other call is leaking any
and so it cannot make a proper inference?
function myFunction(x: number, y: number) {
return x * y || callThatReturnsAny();
}
In this case I would want to type it if I know callThatReturnsAny()
returns a number
function myFunction(x: number, y: number): number {
return x * y || callThatReturnsAny();
}
Although the best solution would just be to type callThatReturnsAny()
so that typescript
can make the inference? But in that case when should you really ever use explicit return types?
Upvotes: 6
Views: 4033
Reputation: 251082
I switch on noImplicitAny
and avoid adding type annotations in almost all cases, except functions. Why? Because I don't want to accidentally return a union type when:
For example, my day goes differently if I start off with:
function example(a: number, b: number) {
vs
function example(a: number, b: number): number {
Here's what happens next...
function example(a: number, b: number) {
if (a > 5) {
return 5;
}
if (b > a) {
return 'b';
}
}
My return type is now number | string | undefined
.
If I use the return type annotation, I get additional help*.
It helps you return the correct type:
In strict mode, it makes sure you return something every time.
* if you like additional help, you'll also have all the strict things switched on.
Upvotes: 11