简体   繁体   中英

Typescript: Type 'undefined' cannot be used as an index type.ts(2538)

I am trying to learn typescript and i do not seem to get my head around how to fix error Type 'undefined' cannot be used as an index type.ts(2538) , keeping default prop values.

Code:

interface PVIconInterface {
  name: string;
  size?: string;
  color?: string;
  rotate?: number
};

// Styled Components
const IconContainer: any = styled.span <{ $fontSize: string, $colorPath: string, $transform: string, theme: any }>`
display: inline-block;
color: ${({ $colorPath, theme }) => getColor($colorPath, theme)};
font-size: ${({ $fontSize }) => $fontSize};
transform: ${({ $transform }) => $transform};
`;

const PVIcon: React.FC<PVIconInterface> = ({ name, size, color, rotate }) => {
 return (
   <IconContainer
     className={`icon-${name}`}
     $colorPath={IconColorMap[color]}  //--- this is where TS gives error coz possible undefined
     $fontSize={IconSizeMap[size]}
     $transform={getTransformStyles(rotate)}
   />
 );
};

PVIcon.defaultProps = {
  color: 'normal',
  size: 'small',
  rotate: 0
};

export default PVIcon;

Any pointers are highly appreciated! Thanks

Typescript compiler knows nothing about defaultProps. So its complains that colour prop could be undefined (as it is declared in PVIconInterface).

Possible solution

Move default props logic into destructuring defaults like that:

...
    const PVIcon: React.FC<PVIconInterface> = ({
  name,
  size = "small",
  color = "normal",
  rotate = 0,
}) => {
  return
...

If you wish to see an other or more complex solutions here is a reference to a good article about defaultProps and TypeScript: medium article

Ps. It is my first stack answer, so if I made the mistake, please correct me:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM