You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建以枚举值为键、对应React函数组件为值的TS类型

创建精准的枚举键-React组件映射类型

要实现每个枚举值对应特定的React组件类型,你可以直接为每个枚举键绑定对应的组件类型,利用typeof获取组件的具体类型,替换掉模糊的React.FC<any>:

import Button from './Button'; // React.FC<ButtonType>
import Select from './Select'; // React.FC<SelectType>
import Checkbox from './Checkbox'; // React.FC<CheckboxType>

enum ComponentType {
  button = 'bla_button',
  select = 'bla_select',
  checkbox = 'bla_checkbox',
}

// 定义枚举值与对应组件类型的精准映射
type ComponentMap = {
  [ComponentType.button]: typeof Button;
  [ComponentType.select]: typeof Select;
  [ComponentType.checkbox]: typeof Checkbox;
};

const componentMap: ComponentMap = {
  [ComponentType.button]: Button,
  [ComponentType.select]: Select,
  [ComponentType.checkbox]: Checkbox,
};

关键说明

  • 使用typeof Button(而非React.FC<any>)可以获取组件的原始类型,包含其特定的Props类型(比如ButtonType),让类型检查更严格。
  • 这个ComponentMap类型会强制要求:当键为ComponentType.button(即'bla_button')时,值必须是Button组件的类型,其他键同理。

如果后续需要扩展枚举和组件,只需在ComponentType和ComponentMap中同步添加对应的条目即可。

内容的提问来源于stack exchange,提问作者frankie303

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:55:12