2

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.

1
  • 1
    Either give hello_map a broader type, like { [key: string]: string }, or greeting a narrower one, like a union of the keys hello_map will have (e.g. via keyof). Commented Jan 4, 2021 at 15:57

1 Answer 1

2

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.