As we develop an Angular2 app (utilizing Angular 13 and Typescript 4.5.5), we heavily rely on string enums, structured like so:
export enum Language {
de = "German",
fr = "French",
it = "Italian",
en = "English"
}
export class Request {
language: Language = Language.de;
... // other properties with enum values
}
The value in the enum (e.g. "Italian") represents what should be shown to users, such as in a drop-down menu. The key in the enum (e.g. 'it') is what we want to store in the backend database when submitting data to our Java-based REST service.
On the server side, we have a corresponding Java enum setup as follows:
public enum Language {
de, fr, it, en
}
@Entity
public class Request {
@Enumerated(EnumType.STRING)
private Language language;
... // other persistent properties
}
The challenge arises when sending data to the backend service - TypeScript serializes the enum to JSON using its value. This causes the service to receive "Italian" instead of "it," leading to issues mapping to the Java enum.
Likewise, when fetching data from the server to display in the Angular interface, the service sends "it" rather than "Italian." Consequently, deserializing JSON back into the TypeScript enum fails.
Is there a way to instruct TypeScript to use the enum key for both serialization and deserialization to/from JSON?
Moreover, can you recommend an approach that effectively separates the user-facing display value from the technical storage value in the database?