Issue
At first, I'd like to reproduce my issue.
Create a new Angular project
ng new ng-ts-strict-issue cd ng-ts-strict-issue
Modify
compilerOptions
intsconfig.json
. Let's setstrict
tofalse
.{ ... "compilerOptions": { ... "strict": false, ... }, ... }
Add a method to the
app.component.ts
.test(p: string): string | null | undefined { if (p === 'test') { return; } return null; }
Run
ng build
⠼ Building...✘ [ERROR] TS7030: Not all code paths return a value. [plugin angular-compiler] src/app/app.component.ts:17:6: 17 │ return; ╵ ~~~~~~ Application bundle generation failed. [3.905 seconds]
Actually, I know this error. The error is related to "noImplicitReturns": true
setting in the tsconfig.json
file. I actually can turn this option off to avoid this issue.
But my question is why the return;
statement will lead to TS7030: Not all code paths return a value.
error only when strict
been set to false
? I actually already returned on every path. Why I violated the noImplicitReturns
rule?
Solution
When the --strictNullChecks
compiler option is disabled, your code is interpreted as:
function test(p: string): string {
if (p === 'test') {
return; // error
}
return null;
}
That is, string | null | undefined
is just string
because null
and undefined
are implicitly contained in every type. According to microsoft/TypeScript#7358, the bare return
statement is therefore considered likely to be a mistake because it does not return a string
, nor does it explicitly return null
or undefined
. This behavior was requested in microsoft/TypeScript#5916.
The error message might not be the best, since it looks like it's saying "not all code paths return" but it really means "not all code paths explicitly return a value".
Anyway, the fix here (assuming you want to keep your compiler options as-is) would be to explicitly return undefined
instead:
function test(p: string): string {
if (p === 'test') {
return undefined; // okay
}
return null;
}
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.