Typescript `enum` from JSON string

前端 未结 4 651
感情败类
感情败类 2020-12-05 17:10

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         


        
相关标签:
4条回答
  • 2020-12-05 17:36

    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;
    }
    
    0 讨论(0)
  • 2020-12-05 17:37

    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

    0 讨论(0)
  • 2020-12-05 17:42

    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.

    0 讨论(0)
  • 2020-12-05 17:43

    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]:
          ...
     }
    
    0 讨论(0)
提交回复
热议问题