user101289
user101289

Reputation: 10422

TypeScript issue with finding key in object

I'm trying to learn typescript as I build a reactjs app, and it seems like I can't help tripping over TS errors. I have built a lookup function (helloMap) to translate one value into another. Example here: https://codesandbox.io/s/withered-worker-yb66l?file=/src/App.tsx

It seems very simple and straightforward, and the sample actually works in codesandbox, but it shows a TS error of (parameter) greeting: string Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Hi: string; "Good day": string; Greets: string; }'. No index signature with a parameter of type 'string' was found on type '{ Hi: string; "Good day": string; Greets: string; }'.ts(7053)

import * as React from "react";
import "./styles.css";

export default function App() {
  const helloMap = (greeting: string) => {
    let hello_map = {
      Hi: "Hola",
      "Good day": "Whattup",
      Greets: "Hello"
    };

    return hello_map[greeting]; // error here
  };

  return (
    <div className="App">
      <h1>{helloMap("Good day")} CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

In my local app this error causes the display to fail to render, and though codesandbox appears to be running a little less strictly it still shows the error in the IDE.

Upvotes: 2

Views: 592

Answers (1)

аlex
аlex

Reputation: 5698

its because of you didn't provided type for hello_map

Should be { [key: string]: string }

import * as React from "react";
import "./styles.css";

export default function App() {
  const helloMap = (greeting: string) => {
    const hello_map: { [key: string]: string } = {
      Hi: "Hola",
      "Good day": "Whattup",
      Greets: "Hello"
    };

    return hello_map[greeting];
  };

  return (
    <div className="App">
      <h1>{helloMap("Good day")} CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Upvotes: 2

Related Questions