Typescript `enum` from JSON string

JsonEnumsTypescript

Json Problem Overview


Is there any way to have a TypeScript enum compatible with strings from JSON?

For example:

enum Type { NEW, OLD }

interface Thing { type: Type }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // false

I would like thing.type == Type.NEW to be true. Or more specifically, I wish I could specify the enum values to be defined as strings, not numbers.

I am aware that I can use thing.type.toString() == Type[Type.NEW] but this is cumbersome and seems to make the enum type annotation confusing and misleading, which defeats its purpose. The JSON is technically not supplying a valid enum value, so I shouldn't type the property to the enum.

So what I am currently doing instead is using a string type with static constants:

const Type = { NEW: "NEW", OLD: "OLD" }

interface Thing { type: string }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // true

This gets me the usage I want, but the type annotation string is way too broad and error prone.

I'm a bit surprised that a superset of JavaScript doesn't have string based enums. Am I missing something? Is there a different way this can be done?


Update TS 1.8

Using string literal types is another alternative (thanks @basaret), but to get the desired enum-like usage (above) it requires defining your values twice: once in a string literal type, and once as a value (constant or namespace):

type Type = "NEW" | "OLD";
const Type = {
	NEW: "NEW" as Type,
	OLD: "OLD" as Type
}

interface Thing { type: Type }

let thing:Thing = JSON.parse(`{"type": "NEW"}`);

alert(thing.type === Type.NEW); // true

This works but takes a lot of boilerplate, enough that I don't use it most of the time. For now I'm hoping the proposal for string enums will eventually make the roadmap.


Update TS 2.1

The new keyof type lookup allows for the string literal type to be generated from the keys of a const or namespace, which makes the definition a little less redundant:

namespace Type {
    export const OLD = "OLD";
    export const NEW = "NEW";
}
type Type = keyof typeof Type;

interface Thing { type: Type }

const thing: Thing = JSON.parse('{"type": "NEW"}');
thing.type == Type.NEW // true

Update TS 2.4

TypeScript 2.4 added support for string enums! The above example becomes:

enum Type {
    OLD = "OLD",
    NEW = "NEW"
}

interface Thing { type: Type }
const thing: Thing = JSON.parse('{"type": "NEW"}');
alert(thing.type == Type.NEW) // true

This looks nearly perfect, but there's still some heartache:

  • You still have to write the value twice, ie OLD = "OLD", and there's no validation that you don't have a typo, like NEW = "MEW"... this has already bitten me in real code.

  • There's some oddities (perhaps bugs?) with how the enum is type checked, its not just a string literal type shorthand, which is what would be truly correct. Some issues I've bumped into:

      enum Color { RED = "RED", BLUE = "BLUE", GREEN = "GREEN" }
    
      type ColorMap = { [P in Color]: number; }
    
      declare const color: Color;
      declare const map: ColorMap;
      map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index signature.
    
      const red: Color = "RED"; // Type '"RED"' is not assignable to type 'Color'.
      const blue: Color = "BLUE" as "RED" | "BLUE" | "GREEN"; // Error: Type '"RED" | "BLUE" | "GREEN"' is not assignable to type 'Color'.
    

    The equivalent code with enum Color replaced by string literal types work fine...

Yeah, I think I have OCD about this, I just want my perfect JS enums. :)

Json Solutions


Solution 1 - Json

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.

Solution 2 - Json

In case someone's still looking at this question in 2021:

> @Aaron wrote in the original question: > > This looks nearly perfect, but there's still some heartache: > > You still have to [...] > > enum Color { RED = "RED", BLUE = "BLUE", GREEN = "GREEN" } > > type ColorMap = { [P in Color]: number; } > > declare const color: Color; > declare const map: ColorMap; > map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index signature. > // [...] > > > The equivalent code with enum Color replaced by string literal types work fine... > > Yeah, I think I have OCD about this, I just want my perfect JS enums. :)

1. keyof typeof enumObj

Regarding,

> The equivalent code with enum Color replaced by string literal types work fine...

use the typeof and keyof operators in chained conjunction.

type ColorKeys = keyof typeof Color
type ColorMap = { [P in ColorKeys]: number; } // will have strongly typed keys

No more implicit any when accessing map: ColorMap.
This will work with numeric enums as well (which can (and should more often than not) be const).

> From Typescript Handbook - Enums at compile time: > > Even though Enums are real objects that exist at runtime, the keyof keyword works differently than you might expect for typical objects. Instead, use keyof typeof to get a Type that represents all Enum keys as strings.

2. ts-enum-util

Check out ts-enum-util, which offers strongly typed interfaces to (likely) all your enum-related needs.

Solution 3 - Json

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]:
      ...
 }

Solution 4 - Json

> 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

Solution 5 - Json

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaron BeallView Question on Stackoverflow
Solution 1 - JsonFelipe SabinoView Answer on Stackoverflow
Solution 2 - JsonJohannes PilleView Answer on Stackoverflow
Solution 3 - JsonRobert GrabińskiView Answer on Stackoverflow
Solution 4 - JsonbasaratView Answer on Stackoverflow
Solution 5 - JsonRyan BurbidgeView Answer on Stackoverflow