网站搜索

reactjs - TypeScript | 无法对自定义类型对象进行循环


我正在尝试从自定义响应数据对象返回一个 [键, 值] 对,但当我尝试循环访问每个 key[value] 时,它会给我这个错误:

在类型 'IResponse' 上未找到带有参数类型 'string' 的索引签名

或

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IResponse'

这是我的 Detail.tsx:

interface IResponse {
  birth_year: string;
  created: string;
  edited: string;
  eye_color: string;
  films: string[];
  gender: string;
  hair_color: string;
  heigth: string;
  homeworld: string;
  mass: string;
  name: string;
  skin_color: string;
  species: string[];
  startships: string[];
  url: string;
  vehicles: string[];
}

const Detail = () => {
  const [person, setPerson] = useState<IResponse>({} as IResponse);
  const { id } = useParams();

  useEffect(() => {
    api.get(`people/${id}`).then((res) => {
      if (res.data) setPerson(res.data as IResponse);
    });
  }, [id]);

  function printValues() {
    return Object.keys(person).map((key) => (
      <li>
        {key}:{person[key]}
      </li>
    ));
  }

  return <ul>{printValues()}</ul>;
};

我的问题是:为什么这段代码:

function objectEntries() {
    const a = "name";
    const entries = person[a];
    console.log(entries);
  }

  objectEntries();

工作正常,而在 printValues 函数中就不行吗?

答案#1

我在这里看到两个不同的问题。首先,你必须调用打印值 return <ul>{printValues()}</ul>。其次,你没有处理在数据获取之前第一次渲染时 person.data 为空的情况。

评论后的更新:好吧,既然你有这些,实际修复类型错误的方法是这样的

    let key: keyof IResponse['data'];
    for (key in person.data) {

问题是你没有任何字符串类型的键。所以你需要说明你正在使用那个对象的键

如果你不喜欢那种语法,你总是可以改用以下方式

for (let [key, value] in Object.entries(person.data))

答案#2

我只需要告诉 TypeScript,该对象可以在 IResponse 接口上访问 [key: string]: value: any!

像 :

interface IResponse {
  [key: string]: your-value-type
  [...]
}

相关文章