TypeScript | 无法循环遍历自定义类型的对象

3
我试图从自定义响应数据对象中返回[key, value]对,但是当我尝试循环遍历每个key[value]时,它会给我这个错误:No index signature with a parameter of type 'string' was found on type 'IResponse' 或者 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函数中出现问题了?

2个回答

2

我看到这里有两个不同的问题。首先,您需要调用打印值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))

好的,我在发问题之前并没有完成代码,非常抱歉,谢谢。但是关于错误怎么办呢?我甚至无法从一个简单的对象中循环。 - Zoey
1
由于您已经修复了其他错误,因此更新了答案。 - topched

0

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

例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接