首页 > 解决方案 > 打字稿:类型“未定义”不能用作索引类型.ts(2538)

问题描述

我正在尝试学习打字稿,但我似乎不知道如何修复错误Type 'undefined' cannot be used as an index type.ts(2538),保持默认道具值。

代码:

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;

任何指针都非常感谢!谢谢

标签: javascriptreactjstypescript

解决方案


Typescript 编译器对 defaultProps 一无所知。所以它抱怨颜色道具可能是未定义的(正如它在 PVIconInterface 中声明的那样)。

可能的解决方案

将默认道具逻辑移动到解构默认值中,如下所示:

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

如果您希望看到其他或更复杂的解决方案,请参考一篇关于 defaultProps 和 TypeScript 的好文章:medium article

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


推荐阅读