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

React TypeScript项目中声明映射属性名,解决never类型报错

问题原因

你在IProps里把commentsData定义为[],在TypeScript中,这种写法表示空数组类型,而非“包含任意元素的数组”。空数组不存在任何元素,所以调用map时,回调函数里的comment类型会被推断为never,自然无法访问name属性。另外,fetch返回的data未指定类型,TypeScript无法推断其结构,也会加剧类型推断异常。

解决方法

1. 定义单个评论的类型接口

根据JSONPlaceholder的comments接口返回结构,先明确单个评论的类型:

interface IComment {
  id: number;
  name: string;
  email: string;
  body: string;
  postId: number;
}

2. 修改Props接口的数组类型

把IProps里的commentsData改为IComment[],告诉TypeScript这是一个包含IComment类型元素的数组:

interface IProps {
  commentsData: IComment[];
}

3. 给fetch返回的数据指定类型

在res.json()处指定类型,让TypeScript明确返回的数据结构:

const data = await fetch('https://jsonplaceholder.typicode.com/comments')
  .then((res) => res.json() as IComment[]);
修改后的完整代码
interface IComment {
  id: number;
  name: string;
  email: string;
  body: string;
  postId: number;
}

interface IProps {
  commentsData: IComment[];
}

const CommentList: React.FC<IProps> = ({ commentsData }) => {
  return (
    <div>
      {commentsData.map(comment => (
        <div key={comment.id}>
          {comment.name}
        </div>
      ))}
    </div>
  )
}

export const getStaticProps = async ()=> {
  const data = await fetch('https://jsonplaceholder.typicode.com/comments')
    .then((res) => res.json() as IComment[]);
  return {
    props: {
      commentsData: data
    }
  }
}

export default CommentList;

补充说明

  • 给map渲染的元素加上key属性(用comment.id),符合React列表渲染规范,避免控制台警告。
  • 明确类型后,TypeScript可以提供代码提示,同时彻底解决类型错误问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:30:16