Sometimes you want to specify in your application multiple allowed values. For example, you might have a method which allows you to perform server requests and the only allowed values are; GET, POST, UPDATE, DELETE and PUT.
Ideally you want to prevent any developer from calling a method with an invalid value. Normally you would use an enum for this, most languages support the use of an enum which might be used for this purpose.
Unfortunately, in TypeScript, enums only support numeric values, not strings. Although, there is an issue here which is calling for it to be extended to strings and other types, like other languages such as C++ allow.
In an ideal world it would be nice to be able to do this in TypeScript:
enum stateEnums {
"on",
"off"
}
export class MyClass {
private componentState: stateEnums;
on() {
this.componentState = "on";
}
off() {
this.componentState = "off";
}
}
Except, because we can’t use an enum in this way, we can use a type instead, the end result isn’t too different:
type stateEnums = "on" | "off";
export class MyClass {
private componentState: stateEnums;
on() {
this.componentState = "on";
}
off() {
this.componentState = "off";
}
}
Not only that, but you can also add in a boolean and possibly other values into the mix as well. You are essentially creating a map of values that will be checked when the value utilising the type is changed. Akin to a “only allow these values and none other”
type stateEnums = "on" | "off" | boolean;
export class MyClass {
private componentState: stateEnums;
on() {
this.componentState = "on";
}
off() {
this.componentState = "off";
}
onTrue() {
this.componentState = true;
}
offFalse() {
this.componentState = false;
}
}
Conclusion
You probably already knew the above, but if not, hopefully this helped you. I am quite knew to the TypeScript side myself, so if there is an even better way of achieving the above (perhaps changing how enums work), then feel free to leave a comment and enlighten us.