Home > Net >  Boolean truthiness narrowing not working in Typescript
Boolean truthiness narrowing not working in Typescript

Time:09-12

I've checked similar questions and cannot find any examples like mine. I am using a function to narrow down a boolean option in an if/else clause, but it only works when defined explicitly, not using the function.

Here is the code I am working with—

TYPES

type SimpleCellContent = string | number;
type ComplexCellContent = {
  content: SimpleCellContent;
  formatter: (content: any) => string;
  class?: string;
  link?: string;
  linkClass?: string;
};
type CellContent = SimpleCellContent | ComplexCellContent;

LOGIC

const isSimpleContent = (cellData: CellContent) => {
  return typeof cellData === 'string' || typeof cellData === 'number' || typeof cellData === 'undefined';
};

const extractContent = (cellData: CellContent) => {
  if (isSimpleContent(cellData)) {
    return cellData;
  } else if (typeof cellData.content !== 'undefined') { // <---  ERROR !!!            
  • Related