在对象中查找键时出现TypeScript问题



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

它看起来非常简单明了,示例实际上在代码沙盒中工作,但它显示了(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)的TS错误

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>
);
}

在我的本地应用程序中,这个错误导致显示无法呈现,尽管codesandbox似乎运行得不那么严格,但它仍然在IDE中显示错误。

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

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

最新更新