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

如何为React TypeScript中的map方法添加类型标注?

解决React TypeScript中map遍历数组时“Property 'id' does not exist on type 'never'”错误

你遇到的问题根源是把authors的类型定义成了空数组[],TypeScript会自动将其推断为never[](永远为空的数组),遍历的时候每个元素的类型是never,自然无法访问id和author_name属性。

解决方法很简单,只需明确数组元素的类型:

步骤1:定义单个作者对象的类型

先声明每个作者对象的结构,匹配你的数据格式:

// 根据实际数据类型调整id的类型(比如number或string)
type Author = {
  id: number | string;
  author_name: string;
};

步骤2:修正Props中的authors类型

把原来的空数组类型[]改成Author[],让TypeScript知道这是一个Author对象组成的数组:

type Props = {
  authors: Author[];
  onFinish: () => void; // 建议把空函数类型改成明确的void返回值
};

修改后的完整代码

import { useState, FC } from 'react';

type Author = {
  id: number | string;
  author_name: string;
};

type Props = {
  authors: Author[];
  onFinish: () => void;
};

const NewTask: FC<Props> = ({ authors, onFinish }) => {
  // 补充你用到的useState声明,避免未定义错误
  const [author, setAuthor] = useState<string>('');
  
  return (
    <select
      onChange={(e) => setAuthor(e.target.value)}
      defaultValue="select"
    >
      <option value="select" disabled>
        Select Author
      </option>
      {authors.map((author) => (
        <option key={author.id} value={author.author_name}>
          {author.author_name}
        </option>
      ))}
    </select>
  )
}

export default NewTask;

另外注意:你的代码里用到了setAuthor但没声明对应的useState,记得补充,否则会出现新的未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:40:07