当尝试从数组中查找带有项的对象的键时,出现错误...
Element implicitly has an 'any' type because type has no index signature
我在此沙箱https://codesandbox.io/s/affectionate-pasteur-kj5h0
中重新创建了它我拍了一张屏幕截图,以防错误在此处https://i.imgur.com/sq6Yqez.png显示
答案 0 :(得分:2)
import * as React from "react";
import { render } from "react-dom";
import { useEffect, useState } from "react";
type X = "fname" | "lname" | "age" | "height";
const App: React.FC = props => {
const [state, setState] = useState<{ array1: X[] }>({ array1: [] });
const Translations: {
[key: string]: {
fname: string;
lname: string;
age: string;
height: string;
};
} = {
en: {
fname: "First Name",
lname: "Last Name",
age: "Age",
height: "Height"
},
cn: {
fname: "名字",
lname: "姓",
age: "年龄",
height: "高度"
}
};
const object1 = Translations["en"];
useEffect(() => {
const array1: X[] = ["fname", "lname", "age", "height"];
setState({ ...state, array1 });
}, [state]);
return (
<div className="App">
<ul>
{state.array1.map((item: X, index: number) => (
<li key={index}>{object1[item]}</li>
))}
</ul>
<p>{object1.fname}</p>
</div>
);
};
const rootElement = document.getElementById("root");
render(<App />, rootElement);
https://codesandbox.io/s/empty-breeze-kqpqg
或者使其更清洁并干燥,可以执行以下操作: https://codesandbox.io/s/angry-https-rc66o?fontsize=14
答案 1 :(得分:0)
添加索引签名将使TypeScript知道类型是什么。 您可以这样做以消除错误
const Translations: {
[key: string]: {
fname: string;
lname: string;
age: string;
height: string;
[key: string]: string;
};
} = {
en: {
fname: "First Name",
lname: "Last Name",
age: "Age",
height: "Height"
},
cn: {
fname: "名字",
lname: "姓",
age: "年龄",
height: "高度"
}
};