我正在尝试使用React属性作为访问对象的关键字。根据属性type是“实体”还是“大纲”,将决定我使用的是什么数据。嵌套的"solid“和"outline”对象中的对象键是不同的,因此Typescript会报错,因为它说它可能无法访问该键。如何让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;typescript错误是:
// 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)发布于 2021-09-26 02:01:08
简而言之:你不能。至少,安全地。嗯,算是吧。
如果你想要一些类型安全,你首先需要缩小每种情况的联合范围,如下所示:
function matchIcon(props: ConditionalProps) {
if (props.type === "outline") {
return icons[props.type][props.iconName];
}
if (props.type === "solid") {
return icons[props.type][props.iconName];
}
}这有点多余,但它是安全的。
另一种方法是抑制错误,但降低代码的安全性:
const text2 =
icons[props.type][
props.iconName as keyof typeof icons.solid & keyof typeof icons.outline
];因为icons[props.type]可以同时为icons.outline和icons.solid,所以我们需要传递一个同时满足这两种情况的iconName值。keyof typeof icons.solid & keyof typeof icons.outline只是可能值的一个子集,如果同时为outline或solid提供这些值,它仍然可以工作。我们主要是在欺骗编译器。
https://stackoverflow.com/questions/69331184
复制相似问题