打字稿|无法循环自定义类型对象

时间:2020-06-17 20:52:24

标签: reactjs typescript

我正在尝试从自定义响应数据对象返回一个[键,值]对,但是当我尝试遍历每个键[值]时,它给了我这个错误:

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 个答案:

答案 0 :(得分:1)

我在这里看到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))

答案 1 :(得分:0)

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

喜欢:

interface IResponse {
  [key: string]: your-value-type
  [...]
}
相关问题