Typescript `enum` from JSON string

前端 未结 4 676
感情败类
感情败类 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;
    }
    

提交回复
热议问题