请考虑以下函数:
function foo(check: boolean){
if(check){
return 123;
}
}
为什么隐式返回类型只有number
而不是number | void
?
堆叠闪光灯:https://stackblitz.com/edit/typescript-jwy5xn?file=index.ts
请考虑以下函数:
function foo(check: boolean){
if(check){
return 123;
}
}
为什么隐式返回类型只有number
而不是number | void
?
堆叠闪光灯:https://stackblitz.com/edit/typescript-jwy5xn?file=index.ts
这里的主要问题似乎是您没有使用the --strictNullChecks
compiler option,这是the --strict
suite of compiler options的一部分,它或多或少被认为是一组"标准"的类型安全特性,强烈建议您使用它.
如果禁用--strictNullChecks
,则认为值null
和undefined
可分配给所有其他类型,并被它们吸收.任何可能返回number
或undefined
的操作都将显示为仅返回number
.这并不是很好.
如果启用--strictNullChecks
,那么您将看到函数的返回类型是union number | undefined
,这有望满足您的需求.
(请注意,number | undefined
与number | void
不是exactly.但void
和undefined
之间的关系有些模糊,我认为,与你为什么只看到number
没有直接关系,我认为这是真正的问题.如果你想了解更多,你可以看看Why is undefined assignable to void?或Why does TypeScript have both `void` and `undefined`?等等.)