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)
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.
hello_mapa broader type, like{ [key: string]: string }, orgreetinga narrower one, like a union of the keyshello_mapwill have (e.g. viakeyof).