The error "Element implicitly has an 'any' type because expression of type 'number' can't be used to index type" occurs when we try to access a property of an object without a type definition.

error

Problem

Let us consider the following code which is going to raise the same error as stated above:

import React from "react";

const romanNumbers = { 1: "i", 2: "ii", 3: "iii", 4: "iv", 5: "v", 6: "vi", 7: "vii", 8: "viii" };

const data = ["one", "two", "three", "four", "five", "six"];

function App() {
  return (
    <div>
      {data.map((item, index) => (
        <div>{`${romanNumbers[index + 1]}) ${item}`}</div> //๐Ÿ‘ˆ type error 
      ))}
    </div>
  );
}

export default App;
error code

TypeScript is saying that we have not defined a type for the "romanNumber" object. This could lead to errors such as the wrong usage of an invalid key to access a property in the "romanNumbers" object.

Solution

In order to fix this issue, we need to type the "romanNumbers" object. The easiest way to type an object is to create an interface as follows:

interface romanType {
  [key: number]: string;
}
typing

Then we need to pass the object type to the object as shown below:

const romanNumbers : romanType = { 1: "i", 2: "ii", 3: "iii", 4: "iv", 5: "v", 6: "vi", 7: "vii", 8: "viii" };
assigning typeย 

Now, let's run the entire error free code with proper typing :

import React from "react";

interface romanType {  // ๐Ÿ‘ˆ typing for the "romanNumber" object
  [key: number]: string;
} 

const romanNumbers : romanType = { 1: "i", 2: "ii", 3: "iii", 4: "iv", 5: "v", 6: "vi", 7: "vii", 8: "viii" };  //๐Ÿ‘ˆ type assigned

const data = ["one", "two", "three", "four", "five", "six"];

function App() {
  return (
    <div>
      {data.map((item, index) => (
        <div>{`${romanNumbers[index + 1]}) ${item}`}</div> //๐Ÿ‘ˆ error fixed
      ))}
    </div>
  );
}

export default App;
final code

Now when we try to access the "romanNumber" object with the index, TypeScript knows that the incoming index value is a "number" type and is also the same as the expected key type for accessing this object.

Conclusion

When defining or fetching an object or an array, always define its typing in order to access the values without type errors.