When is it necessary to declare return function type in TypeScript?

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?

728x90

1 Answers When is it necessary to declare return function type in TypeScript?

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:

  1. I forget to return a value
  2. I return a value of the wrong type

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:

Wrong return type

In strict mode, it makes sure you return something every time.

Missing return (strict mode)

* if you like additional help, you'll also have all the strict things switched on.

3 days ago