问题描述
我有一个基于基础的枚举,例如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};
通过这种方式,您可以获得继承的值,但不必重写基础枚举,这可能导致意外行为,因为枚举在定义后应该是恒定的。