[英]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 返回null
或undefined
而函数的返回类型为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 显示函数add2
和add3
的错误。
You can read more about it: strictnullchecks-off and strictnullchecks-on您可以阅读更多相关信息: strictnullchecks-off和strictnullchecks-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.