首先,我想复制我的问题。
1.创建一个新的Angular项目
ng new ng-ts-strict-issue
cd ng-ts-strict-issue
字符串
1.修改tsconfig.json
中的compilerOptions
。让我们将strict
设置为false
。
{
...
"compilerOptions": {
...
"strict": false,
...
},
...
}
型
1.向app.component.ts
添加一个方法。
test(p: string): string | null | undefined {
if (p === 'test') {
return;
}
return null;
}
型
1.运行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]
型
的数据
实际上,我知道这个错误。该错误与tsconfig.json
文件中的"noImplicitReturns": true
设置有关。我实际上可以关闭此选项以避免此问题。
但我的问题是为什么return;
语句只会在strict
被设置为false
时导致TS7030: Not all code paths return a value.
错误?我实际上已经在每个路径上返回了。为什么我违反了noImplicitReturns
规则?
1条答案
按热度按时间dffbzjpn1#
当禁用
--strictNullChecks
编译器选项时,您的代码将被解释为:字符串
也就是说,
string | null | undefined
只是string
,因为null
和undefined
隐式地包含在每个类型中。根据microsoft/TypeScript#7358,裸return
语句因此被认为可能是错误的,因为它不返回string
,也不会显式返回null
或undefined
。此行为在microsoft/TypeScript#5916中请求。错误消息可能不是最好的,因为它看起来像是在说“不是所有的代码路径都返回”,但实际上它的意思是“不是所有的代码路径都显式地返回一个值”。
无论如何,这里的修复(假设你想保持编译器选项不变)将显式返回
undefined
:型
Playground链接到代码