Map json-string from HttpClient-Response to typescript Enum

Map json-string from HttpClient-Response to typescript Enum

Let's assume you make a request in Angular via HttpClient to a BackendApi that answers you with the following JSON:

[{ "firstname": "Peter", "lastname": "Parker", "job": "Superhero" }]

You would then like to map this JSON to a suitable Typescript domain model, such as:

export interface Employee {
    firstname: string;
    lastname: string;
    job: Jobs;
}

As you can see in the Employee Model above, the type of the job-property should be like following typescript Enum:

export enum Jobs {
    None,
    Superhero,
    Developer,
    Accounter,
    Manager
}

But this will NOT work!

Instead, you should use a String-Enum:

export enum Jobs {
    "None" = "None",
    "Superhero" = "Superhero",
    "Developer" = "Developer",
    "Accounter" = "Accounter",
    "Manager" = "Manager"
}

Now the JSON-String 'Superhero' will map correctly to the Jobs String-Enum.