Home > Blockchain >  Property 'X' does not exist on type 'number' - React TypeScript
Property 'X' does not exist on type 'number' - React TypeScript

Time:09-09

I'm mapping over brands, and while it's not loading, I'm displaying each brand properties, and while it's loading, I'm mapping over numbered/indexed array, and displaying skeleton.

In JavaScript it's working fine, but TypeScript thinks it will map over the numbered array and display the brand properties, thus displaying the error: 'Property 'X' does not exist on type 'number', when it tries to access brand.icon, brand.name, and brand?.sites.

{(loading ? Array.from(Array(6).keys()) : brands).map((brand, i, arr) => (
        <Fragment key={i}>
          <Accordion
            TransitionProps={{
              mountOnEnter: true,
              unmountOnExit: true,
            }}
            className={classes.expPanel}
            expanded={expanded === `panel${i   1}`}
            onChange={handleChange(`panel${i   1}`)}
          >
            <AccordionSummary
              className={classes.expPanelSummary}
              expandIcon={<ExpandMore />}
              aria-controls="panel1d-content"
              id="panel1d-header"
            >
              <ListItemIcon className={classes.brandIcon}>
                {loading ? renderSkeleton(28, 28, 'circle') : <Icon>{brand.icon}</Icon>}
              </ListItemIcon>
              {loading ? renderSkeleton() : <Typography>{brand.name}</Typography>}
            </AccordionSummary>
            <AccordionDetails className={classes.expPanelDetails}>
              <Sites sites={brand?.sites} readOnly={readOnly} />
            </AccordionDetails>
          </Accordion>
          {i < arr.length - 1 && <Divider />}
        </Fragment>
      ))}

CodePudding user response:

If you check if brand is a number it will narrow its type:

{typeof brand === "number" ? renderSkeleton(28, 28, 'circle') : <Icon>{brand.icon}</Icon>}
//                                                                     ^ now it's not a number
  • Related