Typescript `enum` from JSON string

前端 未结 4 662
感情败类
感情败类 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: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

提交回复
热议问题