3

I'm trying to return a [key, value] pair from a custom response data object, but when I try to loop over each key[value], it's gives me this error:

No index signature with a parameter of type 'string' was found on type 'IResponse'

or

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

here's my 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>;
};

My question is: Why this code:

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

  objectEntries();

Works fine and in printValues function doesn't?

2 Answers 2

2

I see 2 different issues here. First you have to call print values return <ul>{printValues()}</ul>. Second you are not handling when person.data is empty on the first render before the data is fetched.

Update after comment: Alright since you have these the actual way to fix the type error is like this

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

The issue is you do not have any string type keys. So you need to say you are using the keys of that object

If you dont like that syntax you can always use the following instead

for (let [key, value] in Object.entries(person.data))
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I didn't completed the code before I post the question, sorry and thank you. But what about the error? I can't even loop from a simple obj.
Updated the answer since you have those other errors fixed
0

I only need to say to TypeScript that the object can access a [key: string]: value: any on the IResponse interface!

like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.