stonerose036
stonerose036

Reputation: 301

How to extend enum for Typescript in React

I'm trying to figure out how to extend my types to allow a new value.

I want to pass through the type of inventory I have (window, door, or brick). In a schema I fetch from the backend I access

export enum Type {
  Window = 'window',
  Door = 'door',
  /**
   * Used to indicate that extending this enum is considered a non-breaking
   * change.
   */
  Other = '@@other',
}

later when I pass the value in as a prop I have inventoryType={Collections.Inventory.Type.Window} for one component, inventoryType={Collections.Inventory.Type.Door} for the second, and I want to be able to pass a new value inventoryType={NewInventoryType.Brick} to my third component.

How do I extend my original enum to include Brick?

Here are a couple of things I tried:

const BRICK_KEY = 'brick'

enum BrickType {
  'Brick' = BRICK_KEY
}

export type NewInventoryType = Collections.Inventory.Type.Window | Collections.Inventory.Type.Door | typeof BrickType

Also tried making a 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',
};

However with the second approach if I try to do a check for inventoryType: typeof NEW_INVENTORY_TYPE I get

This condition will always return 'false' since the types 'Record<Type.Window | Type.Door | "Brick", string>' and 'Type' have no overlap.

I think I'm missing something about Typescript enums here and feel a bit like I'm stumbling around in the dark. Can someone help me extend the enum type?

Upvotes: 0

Views: 2300

Answers (1)

CondeGil
CondeGil

Reputation: 97

You can extend enums with this:

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

Upvotes: 1

Related Questions