Dynamically change the value of enum in TypeScript

六月ゝ 毕业季﹏ 提交于 2020-06-27 17:44:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!