Home > Mobile >  Why can undefined be implicitly returned without an error?
Why can undefined be implicitly returned without an error?

Time:11-21

The following example may return a non-number type (undefined)

function foo(x: number): number
{
    if (x != 5) { return x 2; }
    
    // undefined returned here
}

var arg = process.argv[2];
console.log(foo(Number(arg)))

How come I get no type-check error?

CodePudding user response:

You get no compile time error because you have not enabled the noImplicitReturns rule.

Go into your tsconfig.json and add the rule under compilerOptions:

{
  "compilerOptions": {
    /* ... */
    "noImplicitReturns": true,
  },
}

The following error will be emitted now:

function foo(x: number): number {
//                       ^^^^^^ Error: Function lacks ending return statement and return type does not include 'undefined'
    if (x != 5) { return x 2; }
    
    // undefined returned here
}

The error message might differ depending on how you set strictNullChecks ("Not all code paths return a value"). I would recommend setting strictNullChecks to true if that is not already the case.


Playground

  • Related