【问题标题】:How to create a TS type which has enum value as key and corresponding React functional component as valueHow to create a TS type which has enum value as key and corresponding React functional component as value
【发布时间】:2022-12-27 06:44:06
【问题描述】:

Please see the code block below.

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

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

type ComponentMap = {
  [key in ComponentType]: React.FC<any>;
};

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

I want to have a better type for ComponentMap instead of using React.FC&lt;any&gt; so it can infer when the key is 'bla_button', the value must be Button and so on.

【问题讨论】:

    标签: reactjs typescript typescript-typings typescript-generics


    【解决方案1】:

    You'll have to an interface/type which specifies the relational mapping from string key to function component value. You can use the typeof keyword to extract the type from the FC imports, and use indexed access types

    type MapEnumToComponent = {
        'bla_button': typeof Button;
        'bla_select': typeof Select;
        'bla_checkbox': typeof Checkbox;
    }
    
    type ComponentMap = {
      [key in ComponentType]: MapEnumToComponent[key];
    };
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2013-08-31
      • 2022-12-01
      • 2011-03-19
      • 2022-12-01
      • 2022-12-02
      • 2010-11-24
      • 2023-01-09
      • 2022-12-27
      相关资源
      最近更新 更多