簡體   English   中英

如何根據打字稿中的鍵覆蓋枚舉值

[英]how to override enum value based on the key in typescript

我有一個像BasedColor這樣的基於枚舉,我想在其他枚舉上用作AnotherState。 如果無論如何要使用相同的鍵覆蓋該值。 所以我不需要復制關鍵代碼。 我想我可以創建一個新的枚舉並將鍵 abd 分配給另一個值。 但我想知道在打字稿中是否有更好的方法

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

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

你可以這樣做:

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

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

console.log(Colors.First)

TS 中的枚舉只是對象。 因此,您可以將它們分配給它們符合的接口,並且您可以使用擴展運算符... “擴展”一個接口。

// 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'
}

現在我們可以看到擴展是如何工作的:

// 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};

通過這種方式,您可以獲得繼承的值,但不必重寫底層枚舉,這可能導致意外行為,因為枚舉在定義后應該是常量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM