Sometimes, we want to add functions to an enum with TypeScript.
In this article, we’ll look at how to add functions to an enum with TypeScript.
How to add functions to an enum with TypeScript?
To add functions to an enum with TypeScript, we can create a class that has an enum has its instance variable.
For instance, we write
enum Mode {
landscape,
portrait,
}
class Device {
constructor(public mode: Mode) {
console.log(Mode[this.mode]);
}
}
to add the Device
class that takes a Mode
variable as the argument of its constructor.
Then we can use Mode[this.mode]
to get a value dynamically from the Mode
enum.
Conclusion
To add functions to an enum with TypeScript, we can create a class that has an enum has its instance variable.