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!