1

I have the following object defined:

const routes = {
  "/": {},
  "/abc": {},
};

Now I want to access one of the objects within routes using the index with a variable name:

const indextoFind = "/abc";
const item = routes[indextoFind];

Typescript throws:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ "/": {}; "/abc": {}; }'. No index signature with a parameter of type 'string' was found on type '{ "/": {}; "/abc": {}; }'.

The index is clearly a string so I don't know why it won't allow me to access an object using a string variable.

Also, this works perfectly fine:

const item = routes["/abc"];
2

1 Answer 1

2

The reason why this error occurs is most often when you try to specify some kind of string as a key and the TypeScript compiler cannot resolve this type because it can be any string. To solve this issue, you can use something like keyof typeof or just keyof to get the keys of your object.

Example:

const routes = {
  "/": {},
  "/abc": {},
};

const indexToFind: keyof typeof routes = 'someInput'; // will not work
const item = routes[indexToFind];
const otherIndex: keyof typeof routes = '/';
const item2 = routes[otherIndex];

A better and more useful example would be to have some kind of function that expects a key from an object:

const findSomething = (key: keyof typeof routes): Object => {
  return routes[key];
}

Reproduction link

Sign up to request clarification or add additional context in comments.

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.