【问题标题】:Why TypeScript compiler does not give error when function returns undefined while function's return type is number?为什么当函数返回未定义而函数的返回类型是数字时,TypeScript 编译器不给出错误?
【发布时间】:2021-12-31 05:58:05
【问题描述】:

为什么当函数返回nullundefined 而函数的返回类型是number 时,TSC 不报错。

//gives error
//Error : A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)
function add1(a: number, b: number): number {}


// no error
function add2(a: number, b: number): number {
  return undefined;
}

// no error
function add3(a: number, b: number): number {
  return null;
}

【问题讨论】:

  • 我得到了Type 'undefined' is not assignable to type 'number'.(2322),正如预期的那样
  • 启用严格标志

标签: typescript function types return


【解决方案1】:

当类型检查编译器选项 strictNullChecksoff 时,不会出现错误。启用该选项将导致 Typescript 显示函数 add2add3 的错误。

您可以阅读更多相关信息:strictnullchecks-offstrictnullchecks-on

【讨论】:

    【解决方案2】:

    在tsconfig.json文件的“compilerOptions”下添加“strict”:true。

    【讨论】:

      【解决方案3】:

      正如上面提到的@S.M,它是由strict 标志引起的,实际上它是由strictNullChecks 标志引起的。

      当我设置时

      "strict": true,
      

      "strictNullChecks": true,
      

      TSC 给出了我所期望的错误

      【讨论】:

        猜你喜欢
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 2020-03-28
        相关资源
        最近更新 更多