Dynamically change the value of enum in TypeScript

12,669

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

Solution 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 }
Share:
12,669
Omar Huseynov
Author by

Omar Huseynov

Updated on June 07, 2022

Comments

  • Omar Huseynov
    Omar Huseynov almost 2 years

    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?