In Typescript, what is the idiomatic way to have a boolean value assigned for each enum instance?
Say I have an enum for various error codes. For each of the error codes, I have a boolean stating if the error must be exposed to the end user or not. In Java, I would do like,
enum MyError {
ERROR1(true),
ERROR2(false),
ERROR3(false);
private boolean expose;
public boolean shouldExpose() {
return expose;
}
MyError(boolean expose) {
this.expose = expose;
}
}
Here, the boolean info (whether the error must be exposed to user or not) is encapsulated within the enum itself.
MyError myError = MyError.ERROR1;
System.out.println(myError.shouldExpose()); //true
How can I do this in Typescript as TS doesn't allow boolean values in enums? Should I use a class
or a type
here?
The goal is to have the boolean information contained in the enum/class/type. Hence, I don't want to create a wrapper type like
{
error: MyError
expose: boolean
}
as it can lead to wrong configuration/mappings (it becomes possible to have MyError.ERROR1
with expose as false or vice-versa for other errors).
You wouldn't try to fit this information about the errors in the enumeration itself. The enumeration is simply for listing (well, enumerating) the errors. Their exposeness should be saved in a mapping between the error and the answer to the "is it exposed?" question.
TypeScript's type system will throw an error if you miss an enumeration in the
IS_EXPOSED
object, so it's completely type-safe.