首页 > 解决方案 > 在对象中查找键的 TypeScript 问题

问题描述

我正在尝试在构建 reactjs 应用程序时学习打字稿,但似乎我不禁被 TS 错误绊倒。我已经构建了一个查找函数 ( helloMap) 来将一个值转换为另一个值。此处示例:https ://codesandbox.io/s/withered-worker-yb66l?file=/src/App.tsx

看起来非常简单明了,并且示例实际上在codesandbox中工作,但是它显示了一个TS错误(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>
  );
}

在我的本地应用程序中,此错误会导致显示无法呈现,尽管 codeandbox 的运行似乎不太严格,但它仍会在 IDE 中显示错误。

标签: javascriptreactjstypescript

解决方案


这是因为您没有为 hello_map 提供类型

应该是 { [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>
  );
}

推荐阅读