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

TypeScript报错:类型'String'无法索引React动态组件名称映射

解决React转TypeScript时动态图标组件的索引类型报错

报错原因

你的IconButtonProps里icon的类型是宽泛的string,但iconMap的键是固定的"BellIcon"。TypeScript不允许用任意字符串索引只有特定键的对象——因为如果传入iconMap中不存在的字符串,会拿到undefined,引发运行时错误,所以抛出了TS7053类型错误。

修复方案

方案一:类型安全的限定(推荐)

通过keyof typeof生成iconMap键的联合类型,把icon的类型限定为这些合法键,让TypeScript在编译期就拦截无效值。

修改iconButton.tsx:

import { iconMap } from "./icons";

// 自动生成iconMap所有键的联合类型(当前是 "BellIcon")
type IconName = keyof typeof iconMap;

type IconButtonProps = {
  icon: IconName; // 替换原来的string类型
  label?: string;
  direction?: string;
  onClick: () => void;
};

const IconButton = ({ icon, onClick, label }: IconButtonProps) => {
  // 此时icon是合法键,不会触发索引类型错误
  const IconElement = iconMap[icon];
  
  return (
    <button onClick={onClick}>
      <IconElement />
      {label && <span>{label}</span>}
    </button>
  );
};

方案二:兼容任意字符串(需处理无效情况)

如果必须允许icon为任意字符串,给iconMap添加字符串索引签名,同时要处理图标不存在的场景:

修改icons/index.ts:

import { BellIcon } from "./BellIcon";

// 添加字符串索引签名,声明所有键都是字符串,对应值为图标组件类型
export const iconMap: { [key: string]: (props: any) => JSX.Element } = {
  BellIcon
};

然后在组件中处理IconElement为undefined的情况:

const IconButton = ({ icon, onClick, label }: IconButtonProps) => {
  const IconElement = iconMap[icon];
  
  // 图标不存在时返回null或默认图标
  if (!IconElement) return null;
  
  return (
    <button onClick={onClick}>
      <IconElement />
      {label && <span>{label}</span>}
    </button>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:35:11