问题
Have a look at the following code:
// typescript enum example
enum foo { ONE = 1, TWO = 2, THREE = 3 }
Is it possible to change the value of ONE to 0 in runtime? If yes, how?
回答1:
I don't think the typescript compiler will allow this. But why would you want to change an enum? The whole point is to have named constant values. If you want them to change, why not just use something like this:
const foo = {
ONE: 1,
TWO: 2,
THREE: 3
}
回答2:
Is it possible to change the value of ONE to 0 in runtime? If yes, how?
You can always use a type assertion:
// typescript enum example
enum foo { ONE = 1, TWO = 2, THREE = 3 }
(foo as any).ONE = 0;
More : https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html But I don't recommend it.
Why not just write the following in the first place?:
enum foo { ONE = 0, TWO = 2, THREE = 3 }
来源:https://stackoverflow.com/questions/37366885/dynamically-change-the-value-of-enum-in-typescript