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
相关产品推荐
相关产品推荐

