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

React中使用JSX.Element定义TS Interface出现类型错误如何解决

问题原因

你定义的RowsData是单个行对象的类型,但rows实际是由多个RowsData对象组成的数组,给rows标注的类型和实际值类型不匹配,因此触发了报错。

修复方案

把rows的类型从RowsData调整为数组类型RowsData[]即可,修改后完整代码如下:

interface RowsData {
  [key: string]: string | number | JSX.Element;
}

const rows: RowsData[] = [
  { id: 1, name: 'A', action: <div style={{ color: 'blue' }}> Hello </div> },
  { id: 2, name: 'B', action: <div style={{ color: 'blue' }}> World </div> },
  { id: 3, name: 'C', action: <div style={{ color: 'blue' }}> Foo </div> }
];

可选优化(更严谨的类型定义)

如果你的行对象字段固定只有id、name、action三个,不需要支持动态字符串key,建议直接明确声明字段类型,避免索引签名带来的不必要的类型宽松:

interface RowsData {
  id: number;
  name: string;
  action: JSX.Element;
}

const rows: RowsData[] = [
  { id: 1, name: 'A', action: <div style={{ color: 'blue' }}> Hello </div> },
  { id: 2, name: 'B', action: <div style={{ color: 'blue' }}> World </div> },
  { id: 3, name: 'C', action: <div style={{ color: 'blue' }}> Foo </div> }
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:54:03