1

When trying to find a key of an object with an item from an array I get an error...

Element implicitly has an 'any' type because type has no index signature

I recreated it in this sandbox https://codesandbox.io/s/affectionate-pasteur-kj5h0

I took a screenshot in case the error does show for any reason here https://i.stack.imgur.com/PwCbR.png

Bill
  • 4,614
  • 13
  • 77
  • 132
  • Posting the code would help. I think you can can add/define type for object1 in the following way: `const object1:{[key:string]:TheType}` – HMR Oct 05 '19 at 14:36
  • 1
    Possible duplicate of [How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?](https://stackoverflow.com/questions/32968332/how-do-i-prevent-the-error-index-signature-of-object-type-implicitly-has-an-an) – saurabh Oct 05 '19 at 14:39

2 Answers2

2
import * as React from "react";
import { render } from "react-dom";
import { useEffect, useState } from "react";

type X = "fname" | "lname" | "age" | "height";
const App: React.FC = props => {
  const [state, setState] = useState<{ array1: X[] }>({ array1: [] });

  const Translations: {
    [key: string]: {
      fname: string;
      lname: string;
      age: string;
      height: string;
    };
  } = {
    en: {
      fname: "First Name",
      lname: "Last Name",
      age: "Age",
      height: "Height"
    },
    cn: {
      fname: "名字",
      lname: "姓",
      age: "年龄",
      height: "高度"
    }
  };

  const object1 = Translations["en"];

  useEffect(() => {
    const array1: X[] = ["fname", "lname", "age", "height"];
    setState({ ...state, array1 });
  }, [state]);

  return (
    <div className="App">
      <ul>
        {state.array1.map((item: X, index: number) => (
          <li key={index}>{object1[item]}</li>
        ))}
      </ul>
      <p>{object1.fname}</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);

https://codesandbox.io/s/empty-breeze-kqpqg

Or to make it cleaner and DRY it up you can do : https://codesandbox.io/s/angry-https-rc66o?fontsize=14

Damian Green
  • 6,895
  • 2
  • 31
  • 43
  • How to handle the case if I have some extra translations like this? https://codesandbox.io/s/bitter-tree-gzgl3 – Bill Oct 05 '19 at 14:46
  • you'd add `gender` to your interface `Y` ( https://codesandbox.io/s/confident-pasteur-ql9qq) – Damian Green Oct 05 '19 at 14:48
0

Adding an index signature will let TypeScript know what the type should be. You can do this to get rid of the error

const Translations: {
[key: string]: {
  fname: string;
  lname: string;
  age: string;
  height: string;
  [key: string]: string;
};
} = {
en: {
  fname: "First Name",
  lname: "Last Name",
  age: "Age",
  height: "Height"
},
cn: {
  fname: "名字",
  lname: "姓",
  age: "年龄",
  height: "高度"
}
};
ibtsam
  • 1,620
  • 1
  • 10
  • 10