Typescript:类型'undefined'不能用作索引类型.ts(2538)

时间:2020-08-14 04:47:45

标签: javascript reactjs typescript

我正在尝试学习打字稿,但似乎并没有设法解决错误Type 'undefined' cannot be used as an index type.ts(2538),保持默认prop值。

代码:

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;

任何指针都受到高度赞赏!谢谢

1 个答案:

答案 0 :(得分:2)

Typescript编译器对defaultProps一无所知。因此,它抱怨说color prop可能是不确定的(正如它在PVIconInterface中声明的那样)。

可能的解决方案

将默认属性移动到破坏默认值的方式中,例如:

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

如果您希望看到其他或更复杂的解决方案,请参考这里有关defaultProps和TypeScript的优秀文章:medium article

Ps。这是我的第一个堆栈答案,所以如果我犯了错误,请纠正我:)