I have a jhipster project and they just chanced the enum from this:
export enum DeclarationStatus {
NEW = 'NEW',
DRAFT = 'DRAFT',
APPROVED_BY_FREELANCER = 'APPROVED_BY_FREELANCER',
APPROVED_BY_CLIENT = 'APPROVED_BY_CLIENT',
APPROVED = 'APPROVED'
}
to this:
export enum DeclarationStatus {
NEW,
DRAFT,
APPROVED_BY_FREELANCER,
APPROVED_BY_CLIENT,
APPROVED
}
First I could do a comparison like this:
status === DeclarationStatus.APPROVED_BY_FREELANCER;
But now that does not work any more because the enum is actually a number. This does work how ever:
DeclarationStatus[''+status] === DeclarationStatus.APPROVED_BY_FREELANCER;
So my question is which is better. Or is there even a 3rd option?
I set this question to answered. The Jhipster community reverted the change to initialized. So then comparison is easy again.
Thanks to @vicpermir who made it happen.
The problem here is that the string enum is not initialized. As long as your enums are not defined as const
you can make a very similar comparison as your old method.
status === DeclarationStatus[DeclarationStatus.APPROVED_BY_FREELANCER];
In other words, the following should work:
enum Initialized {
A = 'A',
B = 'B'
}
enum NotInitialized { // equivalent to
A, // A = 0,
B // B = 1
}
status = 'A';
// String enum initialized
let test1 = (status === Initialized.A); // true
// String enum not initialized
let test2 = (status === NotInitialized.A); // false
let test3 = (status === NotInitialized[NotInitialized.A]); // true :)
In the official github repo for the JHipster Generator there is a recently merged pull request (PR#11218) that fixes this problem for React and forces the generator to always initialize string enums.
Remember that, as described in the JDL docs, you can also force this initialization:
enum DeclarationStatus {
NEW (NEW),
DRAFT (DRAFT)
}
More info about TypeScript Enums can be found here.