I've searched for similar queries but couldn't find any identical to mine. My problem arises when I try to use a function to narrow down a boolean option in an if/else statement, as it only seems to work when explicitly defined and not through the function.
Below is the snippet of code I'm having trouble with—
VARIANTS
type BasicCellData = string | number;
type AdvancedCellData = {
content: BasicCellData;
formatter: (content: any) => string;
class?: string;
link?: string;
linkClass?: string;
};
type CellData = BasicCellData | AdvancedCellData;
PROCESS
const isBasicContent = (cellInfo: CellData) => {
return typeof cellInfo === 'string' || typeof cellInfo === 'number' || typeof cellInfo === 'undefined';
};
const retrieveContent = (cellInfo: CellData) => {
if (isBasicContent(cellInfo)) {
return cellInfo;
} else if (typeof cellInfo.content !== 'undefined') { // <--- ERROR !!! 🚨
return cellInfo.content;
} else {
throw new Error('Invalid cell data: ' + JSON.stringify(cellInfo));
}
};
The error message states…
Property 'content' does not exist on type 'CellData'.
Property 'content' does not exist on type 'string'. ts(2339)
Interestingly, when I replace isBasicContent(cellInfo)
with the exact same conditional check from the function (
typeof cellInfo === 'string' || typeof cellInfo === 'number' || typeof cellInfo === 'undefined'
), everything works perfectly without any errors.
Why does this discrepancy occur between using a standalone condition and a function?