【问题标题】:how to override enum value based on the key in typescript如何根据打字稿中的键覆盖枚举值
【发布时间】:2020-12-30 07:47:43
【问题描述】:

我有一个像BasedColor 这样的基于枚举,我想在其他枚举上用作AnotherState。如果无论如何要使用相同的键覆盖该值。所以我不需要复制密钥代码。我想我可以创建一个新的枚举并将键 abd 分配给另一个值。但我想知道在打字稿中是否有更好的方法来做到这一点

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

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

【问题讨论】:

  • 抱歉,查看您的标签,您使用的是什么版本的 TypeScript?
  • 所以你想让AnotherState“扩展”BasedColor,还要加上'light '前缀?
  • 我实际上有 3.8
  • 不,我想用 anotherState 替换 basedColor 中枚举名称的值
  • 输出到底应该是什么?它应该包含Third 还是应该只包含First = 'light red', Second = 'light blue'

标签: typescript typescript2.0 typescript1.8 typescript1.5


【解决方案1】:

你可以这样做:

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

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

console.log(Colors.First)

【讨论】:

  • 如果我有很多名字需要替换枚举上的值怎么办?
【解决方案2】:

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

通过这种方式,您可以获得继承的值,但不必重写底层枚举,这可能会导致意外行为,因为枚举在定义后应该是常量。

【讨论】:

  • 实际上我的问题更像是如何避免重写// Our custom state enum AnotherState { first = 'light blue', second = 'light red' },因为我已经用名称firstsecond编写了enumBaseState
猜你喜欢
  • 1970-01-01
  • 2022-08-03
  • 1970-01-01
  • 2020-05-19
  • 2018-09-18
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 2019-12-27
相关资源
最近更新 更多