javascript - 在对象中查找键的 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 中显示错误。
解决方案
这是因为您没有为 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>
);
}
推荐阅读
- c# - C# VSTO Excel 插件:如何从插件 ThisAddIn_Startup 访问功能区控件?
- html - 如何使文本动态中断或转到下一行?
- windows - PowerShell 如何从网络驱动器访问文件?
- c# - Visual Studio C# 为游戏发送输入
- php - 将较大的字符串值转换为数字 laravel。(int) 给出错误的值
- angular - 在 Angular HTTP 拦截器中对拦截函数进行单元测试
- json - 使用正则表达式测试条件过滤 JSON 对象数组
- sql - PL/SQL 包 - 在包中调用过程
- azure - ARM 模板循环/循环依赖解析
- javascript - 更改 select2 ajax 标记中的选项数据值