Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript enum encapsulating a boolean value per enum instance

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).

like image 676
user7 Avatar asked Oct 27 '25 10:10

user7


1 Answers

You might want to give up on actual enums and instead make your own set of constants. It's more verbose but it might meet your needs.

const MyError = {
  error1: {
    name: 'ERROR1',
    expose: true
  },
  error2: {
    name: 'ERROR2',
    expose: false
  },
  error3: {
    name: 'ERROR3',
    expose: false
  }
} as const;

type MyError = typeof MyError[keyof typeof MyError]


function x(err: MyError) {
  console.log(err);
}

x(MyError.error1);
x({name: 'ERROR1', expose: true});
x({name: 'ERROR1', expose: false}); // EXPECTED ERROR

function getError(): MyError {
  return MyError.error1;
}

var e: MyError = getError();
console.log(MyError.error1 == e);  // true
console.log(MyError.error2 == e);  // false

Playground link

like image 93
Lesiak Avatar answered Oct 28 '25 23:10

Lesiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!