简体   繁体   中英

how to override enum value based on the key in typescript

I have one based enum like BasedColor that I would like to use on other enum as AnotherState. If there is anyway to override the value with the same key. so I do not need to duplicate the key code . I guess I can create a new enum and duplicated the key abd assign to another value. but I am wondering if there is a better way to do it in typescript

enum BasedColor 
{
    First= 'red',
    Second = 'blue'
}

enum AnotherState
{
    First= 'light red',
    Second = 'light blue'
    Third = 'from another state third keu'
}

You can do it like this:

enum Colors
{
    First= 'red',
    Second = 'blue'
}

(Colors as any)['First'] = "Dark Red" // <== here

console.log(Colors.First)

enums in TS are just objects. So, you can assign them to interfaces that they conform to, and you can "extend" one using the spread operator ... .

// An interface for the keys a State can have
interface StateKeys {
    first: string;
    second: string;
    third?: string;
}

// Our base state, which we'll extend
enum BaseState {
    first = 'blue',
    second = 'red',
    third = 'magenta'
}

// Our custom state
enum AnotherState {
    first = 'light blue',
    second = 'light red'
}

Now we can see how extending works:

// For the example, we'll just print the state's values
function doSomething() {
    console.log(currentState.first, currentState.second, currentState.third);
}

// Start with our state as the base state
let currentState: StateKeys = BaseState

doSomething(); // Prints "blue, red, magneta"

// Now we extend our base state with another state.
// Note, keys/values in objects to the right will overwrite ones to the left
currentState = {...BaseState, ...AnotherState};

doSomething(); // Prints "light blue, light red, magenta"

// You could also extend the *current* state instead:
currentState = {...currentState, ...AnotherState};

This way you get inherited values but never have to rewrite the underlying enum, which can lead to unexpected behavior since enums are supposed to be constant after definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM