我有一個列舉:
export enum Sections {
Dashboard = "Dashboard",
Select = "Select",
Widget = "Widget",
}
我想為我的反應組件構建一個區分聯合型別的道具。
export type ReduxLocation =
| {
path: Sections;
widget?: never;
}
| {
path: Sections.Widget;
widget: {
id: string;
side?: "left" | "right";
};
};
那么反應組件的其中一個道具將是型別ReduxLocation:
const MyComponent: React.FC<{ reduxLocation: ReduxLocation }> = () => {
// return whatever
}
目標是,如果將 areduxLocation與path中的任何一個一起傳遞Sections,則物件中不需要其他條目reduxLocation。但是,如果path是Sections.Widget,則該widget條目是必需的。
const App = () => {
return (
<div>
<MyComponent
reduxLocation={{
path: Sections.Dashboard
}}
/>
<MyComponent
reduxLocation={{
path: Sections.Dashboard,
widget: { id: 'id' } // <---- errors as expected
}}
/>
<MyComponent
reduxLocation={{
path: Sections.Widget,
widget: { id: 'id' }
}}
/>
<MyComponent
reduxLocation={{
path: Sections.Widget
// <-------------------------- should error but doesnt
}}
/>
</div>
);
}
在上述最后一種情況下MyComponent,我沒有得到所需的 TS 錯誤,即在使用 a 時path: Sections.Widget,該widget屬性也是必需的。我的猜測是因為 usingpath: Sections.Widget也滿足第一種型別 in ReduxLocation,因為path仍然是 type Maps。
我怎樣才能達到預期的結果,在上述情況下強制屬性中的正確組合?
uj5u.com熱心網友回復:
該物件{ path: Sections.Widget }是完全有效的,因為Sections.Widget可分配給Sections它滿足第一個聯合元素的約束。
您可能希望Sections.Widget從path第一個元素中排除。這樣,聯合就可以被恰當地區分,因為每個Section只能分配給一個聯合元素。
export type ReduxLocation =
| {
path: Exclude<Sections, Sections.Widget>;
widget?: never;
}
| {
path: Sections.Widget;
widget: {
id: string;
side?: "left" | "right";
};
};
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508378.html
