Reputation: 1442
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
Upvotes: 1
Views: 4029
Reputation: 1610
Typescript compiler knows nothing about defaultProps. So its complains that colour prop could be undefined (as it is declared in PVIconInterface).
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 :)
Upvotes: 2