Is there any way to have a TypeScript enum compatible with strings from JSON?
For example:
enum Type { NEW, OLD }
interface Thing { type: Type }
l
I've been using converter functions as a stopgap. Hopefully this thread comes to a resolution: https://github.com/Microsoft/TypeScript/issues/1206
enum ErrorCode {
Foo,
Bar
}
interface Error {
code: ErrorCode;
message?: string;
}
function convertToError(obj: any): Error {
let typed: Error = obj as Error;
// Fix any enums
typed.code = ErrorCode[typed.code.toString()];
return typed;
}
but the type annotation string is way too broad and error prone.
Agreed. One quick workaround (if you have the luxury of code generation you can automate this):
interface Thing { type: "NEW" | "OLD" }
These are called string literals in a union. More : https://basarat.gitbooks.io/typescript/content/docs/tips/stringEnums.html
If you are using Typescript before the 2.4 release, there is a way to achieve that with enums by casting the values of your enum to any
.
An example of your first implementation
enum Type {
NEW = <any>"NEW",
OLD = <any>"OLD",
}
interface Thing { type: Type }
let thing:Thing = JSON.parse('{"type": "NEW"}');
alert(thing.type == Type.NEW); // true
Typescript 2.4 has built in support for string enums already, so the cast to any
would be no longer necessary and you could achieve it without the use of String Literal Union Type, which is ok for validation and autocomplete, but not so good for readability and refactoring, depending on the usage scenario.
TS 2.9.2
My solution:
export enum Enums { VALUE1, VALUE2 }
and when I have value from API json:
switch (response.enumValue.toString()) { //can be without toString if we have string value from JSON.
case Enums[Enums.VALUE1]:
...
case Enums[Enums.VALUE2]:
...
}