TS7053报错:用any类型索引对象时元素隐式为any类型如何修复?
错误原因
TS7053报错的核心是类型不匹配:
- 你给
SecondElement的type参数声明为any,TS无法确认它是否是你写的组件映射对象的合法索引 - 原生
select的e.target.value默认返回字符串类型,和你映射对象的数字类型键不匹配,进一步加剧了类型校验失败
修复步骤
- 首先定义合法的type值类型,替换掉any声明
// 提前定义允许的type取值 type AllowedType = 1 | 2 | 3; // 给SecondElement的props明确类型 interface SecondElementProps { type?: AllowedType }
- 给存储type的state加上正确的类型声明
const [type, setType] = useState<AllowedType | undefined>();
- 处理select的返回值,把字符串转成数字匹配键类型
<select value={type} onChange={(e) => setType(Number(e.target.value) as AllowedType)} > {/* 空选项明确赋值为空字符串 */} <option value=""></option> <option value={1}>First</option> <option value={2}>Second</option> <option value={3}>Third</option> </select>
- 改造SecondElement组件,给映射对象明确类型,同时加空值兜底
export default function SecondElement({ type }: SecondElementProps) { // 用Record明确映射对象的键类型为AllowedType const componentMap: Record<AllowedType, JSX.Element> = { 1: <FirstElem />, 2: <SecondElem />, 3: <ThirdElem />, }; // 空值时返回null避免渲染问题 return type ? componentMap[type] : null; }
可选替代方案
如果你不想做数字类型转换,也可以直接把映射对象的键改成字符串类型,就不需要转Number了:
const componentMap: Record<string, JSX.Element> = { "1": <FirstElem />, "2": <SecondElem />, "3": <ThirdElem />, };
内容的提问来源于stack exchange,提问作者user76333
相关产品推荐
相关产品推荐

