I am encountering an issue with the code structure below:
interface Data {
isAvailable: boolean;
}
const foo = (data: Data | undefined, error: boolean) => {
const hasError = error || !data;
if (!hasError) {
if (data.isAvailable) // do something here. this is where I am facing a problem
}
return hasError;
}
When running Typescript, it flags a Object is possibly undefined
error on data
in the if (data.isAvalable)
check, even though I have verified hasError
. A solution could be to add && data
to the if (hasError)
, but this leads to duplicated code. Shouldn't Typescript be able to deduce that data is defined without the explicit check?