Getting typescript error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type"

Viewed 17

I've been trying to resolve a Typescript error I'm receiving without success. I'm new to typescript and read a lot in the internet before I decided to as here.

The code is pretty simple and the code works well otherwise, but cant get around the typescript error:

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; bio: { interests: { hoby: string; }; }; }'. No index signature with a parameter of type 'string' was found on type '{ name: string; bio: { interests: { hoby: string; }; }; }'.

18 return acc?.[curr];

Here is the sample code that results in the error:

/**
 * selected is "swimming" at the end because the reduce function is able to
 * traverse nested properties of the "sample" object
 */

const target = {
  bio: {
    interests: {
      hoby: "swimming"
    }
  }
};
const objectTree = ["bio", "interests", "hoby"];

const selected = objectTree.reduce((acc, curr) => acc?.[curr], target);
0 Answers
Related