简体   繁体   中英

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?

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 number | string | undefined 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM