I currently work an a single-page application (SPA), where we use TypeScript to access web services. In some places, the sent and received data structures use enums to describe the range of allowed values. I tried to use the enums from TypeScript to access the web services in a strongly typed way:
export interface PersonDto {
language: Language;
}
export enum Language {
English,
German,
French,
Itialian
}
When serializing a PersonDto
instance to JSON, the language field is converted to a number and not a string as required by the web service API:
var person = <PersonDto> { language: Language.German }
var json = JSON.stringify(person);
The json
variable now contains:
"{ language: 1 }"
The solution to this problem is to assign the expected string value to each enum member. However, TypeScript only allows numbers as enum member values. But there is a simple solution: Just cast the string literal to any
before assigning:
export enum Language {
English = <any>"English",
German = <any>"German",
French = <any>"French",
Italian = <any>"Italian"
}
The shown TypeScript code is transpiled into the following JavaScript code:
(function (Language) {
Language[Language["English"] = "English"] = "English";
Language[Language["German"] = "German"] = "German";
Language[Language["French"] = "French"] = "French";
Language[Language["Italian"] = "Italian"] = "Italian";
})(exports.Language || (exports.Language = {}));
var Language = exports.Language;
With the shown changes to the enum, the output of the previous serialization code works as expected:
"{ language: "German" }"
Read more about this problem on this GitHub Issue page.
Rico Suter
SOFTWARE ENGINEERING
EDIT
TypeScript