Home > Blockchain >  How to force typescript to require to return undefined rather than having an explicit return?
How to force typescript to require to return undefined rather than having an explicit return?

Time:02-21

Let's take this example:

function maybeString(a: number): string | undefined {
    if (a > 5) {
        return 'ok';
    }
}

This is valid Typescript.

Is there a configuration to force this code to be:

function maybeString(a: number): string | undefined {
    if (a > 5) {
        return 'ok';
    } else {
        return undefined;
    }
}

So always making the return undefined necessary and explicit?

CodePudding user response:

Normally that should already lead to a TS error (link to TS playground). The error should be "Not all code paths return a value.ts(7030)".

Maybe check your tsconfig file and set "noImplicitReturns" to true. If not yet true, this should enable such warnings.

tsconfig.json:

{
  "compilerOptions": {
    "noImplicitReturns": true
  }
}
  • Related