typescript 错误“TS7030:Not all code paths return a value.”由tslog.json中的“strict”:false引起

mitkmikd  于 7个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(148)

首先,我想复制我的问题。
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规则?

dffbzjpn

dffbzjpn1#

当禁用--strictNullChecks编译器选项时,您的代码将被解释为:

function test(p: string): string {
  if (p === 'test') {
    return; // error
  }
  return null;
}

字符串
也就是说,string | null | undefined只是string,因为nullundefined隐式地包含在每个类型中。根据microsoft/TypeScript#7358,裸return语句因此被认为可能是错误的,因为它不返回string,也不会显式返回nullundefined。此行为在microsoft/TypeScript#5916中请求。
错误消息可能不是最好的,因为它看起来像是在说“不是所有的代码路径都返回”,但实际上它的意思是“不是所有的代码路径都显式地返回一个值”。
无论如何,这里的修复(假设你想保持编译器选项不变)将显式返回undefined

function test(p: string): string {
  if (p === 'test') {
    return undefined; // okay
  }
  return null;
}


Playground链接到代码

相关问题