In an Angular2 application (using Angular 13 and Typescript 4.5.5) we use a lot of string enums like this:
export enum Language {
de = "German",
fr = "French",
it = "Italian",
en = "English"
}
export class Request {
language: Language = Language.de;
... // other enum-valued properties like the above
}
The value of the enum (e.g. "Italian") is the value that should be displayed to the user, e.g. in a drop-down. The enum key (e.g. 'it') is what we would like to store in the database when we submit the data to our backend REST service that is implemented in Java.
So in the backend service we have a corresponding Java enum defined as this:
public enum Language {
de, fr, it, en
}
@Entity
public class Request {
@Enumerated(EnumType.STRING)
private Language language;
... // other persistent properties
}
The problem is that when the data is submitted to the backend service, the Typescript enum is serialized to JSON using its value. So the service receives "Italian" instead of "it" and cannot map it to the Java enum.
Similarly, when we try to retrieve data from the backend service to display it in the Angular GUI, the service sends "it" instead "Italian", so the deserialization of JSON to the TypeScript enum also fails.
Is there any way to tell TypeScript that it should use the enum key both when serializing and deserializing an enum to/from JSON?
And more generally, which approach would you suggest for what we're trying to achieve (i.e. separate the display value shown to the user from the technical value to be stored in the database)?