[英]How to extend enum for Typescript in React
我試圖弄清楚如何擴展我的類型以允許新值。
我想通過我擁有的庫存類型(窗戶、門或磚)。 在我從我訪問的后端獲取的模式中
export enum Type {
Window = 'window',
Door = 'door',
/**
* Used to indicate that extending this enum is considered a non-breaking
* change.
*/
Other = '@@other',
}
稍后當我將值作為道具傳遞時,我有一個組件的inventoryType={Collections.Inventory.Type.Door}
inventoryType={Collections.Inventory.Type.Window}
第二個組件的 inventoryType={Collections.Inventory.Type.Door} ,我希望能夠通過為我的第三個組件添加一個新值inventoryType={NewInventoryType.Brick}
。
如何擴展我的原始枚舉以包含 Brick?
以下是我嘗試過的幾件事:
const BRICK_KEY = 'brick'
enum BrickType {
'Brick' = BRICK_KEY
}
export type NewInventoryType = Collections.Inventory.Type.Window | Collections.Inventory.Type.Door | typeof BrickType
還嘗試制作一個 const
export const NEW_INVENTORY_TYPES: Record<
| Exclude<Collections.Inventory.Type, Collections.Inventory.Type.Other>
| typeof BRICK_KEY,
string
> = {
[Collections.Inventory.Type.Window]:
INVENTORY_TYPE_LABELS[Collections.Inventory.Type.Window],
[Collections.Inventory.Type.Door]:
INVENTORY_TYPE_LABELS[Collections.Inventory.Type.Door],
Brick: 'Brick',
};
但是,如果我嘗試檢查inventoryType: typeof NEW_INVENTORY_TYPE
我得到的第二種方法
This condition will always return 'false' since the types 'Record<Type.Window | Type.Door | "Brick", string>' and 'Type' have no overlap.
我想我在這里遺漏了一些關於 Typescript 枚舉的東西,感覺有點像我在黑暗中蹣跚而行。 有人可以幫我擴展枚舉類型嗎?
您可以使用以下方法擴展枚舉:
enum Type {
Window = 'window',
Door = 'door',
Other = '@@other',
}
enum newType {
Brick = "brick"
}
const lastType = { ...Type, ...newType }
console.log(lastType.Window == Type.Window) // true
console.log(lastType.Window == 'window') // true
console.log(lastType.Window == Type['Window']) // true
// and so on
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.