如何为支持的图像制作类型

How can I make a Type for supported images

客户只是想让我用支持的图标名称制作一个类型。我是 typescript 的新手,正在努力制作它。

这是我的 SVG 组件。我在这个组件中有超过 100+ svg。

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;

由于这是一个对象,打字稿编译器会自动推断类型,但在您的情况下,您可以这样做:

const icons = {
  // ...your icons
}

type Icons = {[K in keyof typeof icons]: JSX.Element}

这是一个映射类型,您可以查看有关此的更多信息here

here 是一些关于打字稿中 typeof 关键字的文档

还有一件事,如果您在另一个文件中(或在 React FC 之外)使用图标定义对象会更好,因为看起来对象定义在 React 功能组件内部,如果是这样,它将在每次重新渲染时重新生成,另一种选择是使用 useRef 挂钩,但它只会使事情复杂化

希望对您有所帮助