Fri Apr 14 2023

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

How to resolve the "Element implicitly has an 'any' type because expression of type x can't be used to index type" warning

This one is a common TS warning I come across quite often. The fix is quite simple so let’s get down to where you might meet this error

1const user = {
2 name: "James",
3 age: 29,
4 country: "Germany",
5};
6const userCountry = ["USA", "Germany", "France"].filter(
7 (country) => user[country] // <- this is where the TS warning is
8);

The reason this is happening is that TS is telling us that we have not defined a type for the user object. 

So there are two ways to do what TS wants 

1. You could use a type cast so that the code looks as below

1const userCountry = ["USA", "Germany", "France"].filter(
2 (country) => user[country as keyof typeof user]
3);

Here the keyof typeof user would be a union type that looks like "name" | "age" | "country"

2. You could create a type for the object in question

1interface UserInfo {
2 [key: string]: string | number;
3}
4const user: UserInfo = {
5 name: "James",
6 age: 29,
7 country: "Germany",
8};
9const userCountry = ["USA", "Germany", "France"].filter(
10 (country) => user[country]
11);

This is my favoured approach as the problematic object is now typed, solving the original warning we had + we now have type safety wherever else we are using this object.

If you found this article useful, let me know. Have comments or ideas on more content you would like to see from me? Also, let me know (in the comments below!).

Comments