client just wants me to make a type with the supported icon names. I'm new to typescript and struggling to make it.
here is my SVG component. I have more than 100+ svg in this component.
CustomIcons.tsx
import { IconTypes } from "../../types/types";
const CustomIcons = (props: IconTypes) => {
const icons: any = {
FrameIcon: (
<svg
name="FrameIcon"
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C695.409 238.987 667.885 262.248 636.416 276.436C612.104 287.397 589.793 302.386 564.742 311.911C523.785 327.491 475.861 332.973 430.087 327.163C395.247 322.751 361.653 311.801 333.32 293.793C312.276 280.425 293.787 263.92 275.899 246.561C252.488 223.823 227.286 203.264 202.496 182.058C185.037 167.12 165.098 156.661 147.85 141.479C134.342 129.581 121.111 117.121 107.991 104.784C86.5556 84.6234 64.0287 65.4171 42.9997 44.8476C28.9062 31.0539 13.4654 16.1833 0.432617 0.407227L460.923 -287.339Z"
fill="#232323"
/>
</svg>
),
VectorIcon: (
<svg
name="VectorIcon"
width="632"
height="330"
viewBox="0 0 632 330"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M460.923 -287.339L760.908 192.738C748.744 201.994 736.08 210.636 723.487 219.419C69"
fill="#232323"
/>
</svg>
),
};
return <>{icons[props.name] ? icons[props.name] : undefined}</>;
};
export default CustomIcons;
Since this is an object the typescript compiler will automatically infer the type, but in your case you can do something like this:
const icons = {
// ...your icons
}
type Icons = {[K in keyof typeof icons]: JSX.Element}
this is a mapped type, you can see more information about this here
and here is some documentation about the typeof keyword in typescript
And one more thing, would be better if you define the object with the icons in another file (or outside of the react FC), 'cause looks like the object definition is inside a React functional component and if so, it will be regenerated on every rerender, another option is to use the useRef hook but it'll just complicate things
Hope it helped 😀