我正在尝试学习打字稿,但似乎并没有设法解决错误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;
任何指针都受到高度赞赏!谢谢
Typescript编译器对defaultProps一无所知。因此,它抱怨color prop可能是未定义的(如在PVIconInterface中声明的那样)。
将默认的props逻辑移动到破坏默认值的过程中,如下所示:
...
const PVIcon: React.FC<PVIconInterface> = ({
name,
size = "small",
color = "normal",
rotate = 0,
}) => {
return
...
如果您希望看到其他或更复杂的解决方案,请参考以下有关defaultProps和TypeScript的好文章:中级文章
附言 这是我的第一个堆栈答案,所以如果我犯了错误,请纠正我:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句