I'm coding a component that will return the icon corresponding to the passed prop as follows (simplified version of my app):
import * as icons from "@mui/icons-material";
interface IGenericIconProps {
iconName: keyof typeof icons;
}
export const GenericIcon = ({ iconName }: IGenericIconProps): JSX.Element => {
const Icon = icons[iconName];
return <Icon />;
};
import GenericIcon from './GenericIcon';
interface IUseGenericIconProps {
randomIcon: string; // the error goes away if I change this to 'any'
}
const UseGenericIcon = ({randomIcon}: IUseGenericIconProps): JSX.Element => {
return (
<GenericIcon iconName={randomIcon}/>
)
}
Then in another file I have
import UseGenericIcon from './UseGenericIcon';
enum MyIcons {
Task = "TaskOutlined",
Reminder = "AlarmOutlinedIcon",
Other = "AnnouncementOutlinedIcon",
}
const Calendar = () => {
return (
<UseGenericIcon randomIcon={MyIcons.Task}/>
)
}
This ends up throwing an Typescript error:
Type 'string' is not assignable to type '"Abc" | "AbcOutlined" | "AbcRounded" | "AbcSharp" | "AbcTwoTone" | "AcUnit" | "AcUnitOutlined" | "AcUnitRounded" | "AcUnitSharp" | "AcUnitTwoTone" | "AccessAlarm" | "AccessAlarmOutlined" | ... 9875 more ... | "ZoomOutTwoTone"'.ts(2322)
As noted, I can change the type from string
to any
and it will work, but I would like to know how can I fix this type error for future use. They both seem to be strings to me.
I got the implementation idea from Rendering Material-UI icons from an array