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

Why the error occurs ?

When you create an object in TypeScript, you define the types of each property in the object. For example, you can create an object with a “student” property that is a string, and a “class” property that is also a string.

const str = 'student' as string;

const obj = {
  student: 'Praveen',
  class: '11th',
};

Now, if you want to get the value of a property in the object, you can use the property ‘student’ as a string to access it. For example, you can get the value of the ‘student’ property of an object like this: object[str]. The variable str contains the value ‘student’ so it should return ‘Praveen’.

However, TypeScript can’t be sure that the property you’re trying to access actually exists on the object. So it gives you an error to warn you that you might be doing something wrong.

const str = 'student' as string;

const obj = {
  student: 'Praveen',
  class: '11th',
};

// ⛔️ Error: Element implicitly has an 'any' type
// because expression of type 'string' can't be used
// to index type '{ name: string; }'.
// No index signature with a parameter of type 'string'
// was found on type '{ name: string; }'.ts(7053)
obj[str];

TypeScript is giving you the error because you’re using a string to access a property of an object, but TypeScript can’t be sure that the property actually exists on the object, or that its type is correct.

How to fix the error ?

To fix this error, you can use a special TypeScript operator called keyof to get a type that represents all the possible keys of an object. Then you can use another TypeScript operator called a type assertion to tell TypeScript that you know for sure that the key you’re accessing is one of the keys of the object.

const str = 'student' as string;

const obj = {
  student: 'Praveen',
  class: '11th',
};

console.log(obj[str as keyof typeof obj]); // Output: "Praveen"

So in the code obj[str as keyof typeof obj], the keyof operator is used to get a type that represents all the possible keys of the obj object.

By using typeof obj, TypeScript is able to infer the type of the obj object and ensure that the key being accessed using obj[str as keyof typeof obj] is a valid key of the obj object, without having to explicitly declare the type of the obj object.

Then the as keyword is used to do a type assertion, telling TypeScript that str is one of the keys of the obj object.

I hope this blog helped you fix your problem🙏.

Leave a Comment