typescript - Typescript strictNullChecks error when not possible
问题描述
I am attempting to turn on the strictNullChecks setting for my project, but have a rather curious error in the following snippet of code:
toasters.forEach((toster: ToasterObject) => {
if (toaster.brandName) {
//This line works just fine
let y = toaster.brandName.toLowerCase() === 'test brand name';
//This line has the error
if (!itemsArray.some(item => item.brandName.toLowerCase() === toaster.brandName.toLowerCase())) {
//do stuff
}
}
});
The error message has toaster.brandName
underlined in the if statement with the following error text: error TS2532: Object is possibly 'undefined'.
If the object is fine to use on the y = line above, why would it be a problem to use in the if statement? How can I fix this so it will quit erroring on this?
解决方案
Control flow analysis is hard. The problem here is that the compiler does not know if or when or how a callback will be called. So the narrowing of toaster.brandName
from (presumably) string | undefined
to string
is no longer in effect inside the array.some()
callback. If you want to help the compiler out, you should assign the known-defined value of toaster.brandName
to a const
, which is expected by the compiler to always stay the same, narrow type:
toasters.forEach((toster: ToasterObject) => {
if (toaster.brandName) {
const toasterBrandName = toaster.brandName; // string, now and forever
if (!itemsArray.some(item => item.brandName.toLowerCase() === toasterBrandName.toLowerCase())) {
//do stuff
}
}
});
Hope that helps; good luck!
推荐阅读
- c# - 如何在项目的视图中转换日期时间
- visual-studio-code - vscode-scss 中的自动导入
- php - 带有价格参数的数组过滤 JSON 数据
- c# - 为什么微软支付窗口是空的?
- amazon-web-services - 使用 API 网关和多个 URL 查询字符串参数进行缓存
- javascript - 从文件导入默认和命名导入不起作用?
- android - java.lang.IllegalStateException:pb 在 TopHeadlinesFragment 处不能为空?
- postgresql - 如何获取数据库中定义的外键约束?
- nested - 没有重新计算 HSL 的 CSS 变量
- jquery - 滚动到达部分末尾时更改元素的不透明度