【发布时间】:2021-09-26 01:34:30
【问题描述】:
我正在尝试使用 React 道具作为访问对象的键。根据道具type 是“实心”还是“轮廓”,将决定我使用什么数据。嵌套的“solid”和“outline”对象中的对象键不相同,因此 Typescript 抱怨,因为它说它可能无法访问该键。你如何让打字稿快乐?
代码可以正常工作,但不知道如何消除错误。
const icons = {
outline: {
default: "x1",
icon1: "icon1"
},
solid: {
default: "x2",
icon2: "icon2"
}
} as const;
// If type is solid, you can only choose a solid iconName
// If type is outline, you can only choose an outlined iconName
type ConditionalProps =
| { type: "solid"; iconName: keyof typeof icons.solid }
| { type: "outline"; iconName: keyof typeof icons.outline };
const App = ({type = "outline", iconName = "default"}: ConditionalProps) => {
// Typescript doesn't complain here
const text1 = icons[type];
// TSERROR: Typescript complains here
const text2 = icons[type][iconName];
return (
<div>
<h1>The chosen icon is...</h1>
<h2>{Object.keys(text1)}</h2>
<h2>{text2}</h2>
</div>
);
}
export default App;
打字稿错误是:
// TSERROR
Element implicitly has an 'any' type because expression of type
'"icon2" | "icon1" | "default"' can't be used to index type
'{ readonly default: "defaultOutline"; readonly icon2: "icon2"; }
| { readonly default: "defaultSolid"; readonly icon1: "icon1"; }'.
Property 'icon2' does not exist on type
'{ readonly default: "defaultOutline"; readonly icon2: "icon2"; }
| { readonly default: "defaultSolid"; readonly icon1: "icon1"; }'.ts(7053)
【问题讨论】:
标签: reactjs typescript react-typescript