简体   繁体   中英

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) (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.

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) => {
    let 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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM