简体   繁体   English

为什么 TypeScript 编译器在 function 返回 undefined 而函数的返回类型为数字时不报错?

[英]Why TypeScript compiler does not give error when function returns undefined while function's return type is number?

Why TSC does not give error when function returns null or undefined while function's return type is number .为什么当 function 返回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;
}

add "strict":true under "compilerOptions" in tsconfig.json file.在 tsconfig.json 文件的“compilerOptions”下添加“strict”:true。

You get no error when Type Checking compiler option strictNullChecks is off .当类型检查编译器选项strictNullChecks off时,您不会收到任何错误。 Enabling the option will result in Typescript displaying the error for the functions add2 and add3 .启用该选项将导致 Typescript 显示函数add2add3的错误。

You can read more about it: strictnullchecks-off and strictnullchecks-on您可以阅读更多相关信息: strictnullchecks-offstrictnullchecks-on

as @SM mentioned above it is caused by strict flag indeed it is caused by strictNullChecks flag.正如上面提到的@SM,它是由strict标志引起的,实际上它是由strictNullChecks标志引起的。

when I set当我设置

"strict": true,

or或者

"strictNullChecks": true,

TSC gives error as what I expect TSC 给出了我所期望的错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 TypeScript 会告诉我“函数缺少结束返回语句并且返回类型不包括‘未定义’”,而这些都不为真? - why is TypeScript telling me "Function lacks ending return statement and return type does not include 'undefined'" when neither of those are true? Typescript 错误代码:2366,Function 缺少结束返回语句且返回类型不包括“未定义” - Typescript Error code: 2366, Function lacks ending return statement and return type does not include 'undefined' 当 function 参数类型不匹配时,为什么 TypeScript 不抛出错误? - Why does TypeScript not throw an error when the function argument type is mismatched? 为枚举类型使用常量时,为什么打字稿会出错? - Why does typescript give an error when using a constant for an enum type? 为什么 Typescript 编译器将函数的返回类型推断为“原始类型”,而返回值是已知值? - Why does the Typescript compiler infer return type of functions as `primitive type` while the return value is a known value? 当 function 类型为 FunctionalComponent 时,Typescript 返回错误,但箭头 function 不返回错误 - Typescript returns error when a function type is FunctionalComponent, but not for arrow function TypeScript - 返回返回新实例的函数类型 - TypeScript - Return type of function that returns new instance 为什么TypeScript允许我省略函数的返回类型? - Why does TypeScript allow me to omit the return type of a function? 为什么TypeScript不报“错”function返回类型 - Why does TypeScript not report a "wrong" function return type TypeScript:当外部函数返回“任何”类型时显示错误? - TypeScript: Show an error when an external function returns a type of 'any'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM