簡體   English   中英

TypeScript 在 object 中查找密鑰的問題

[英]TypeScript issue with finding key in object

當我構建一個 reactjs 應用程序時,我正在嘗試學習 typescript,似乎我不禁被 TS 錯誤絆倒。 我建立了一個查找 function ( helloMap ) 來將一個值轉換為另一個值。 此處示例: https://codesandbox.io/s/withered-worker-yb66l?file=/src/App.tsx

看起來非常簡單直接,並且示例實際上在codesandbox中工作,但它顯示了(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>
  );
}

在我的本地應用程序中,此錯誤導致顯示無法呈現,盡管代碼和框的運行似乎不太嚴格,但它仍然在 IDE 中顯示錯誤。

這是因為您沒有為 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>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM