Using an enum as a dictionary key

前端 未结 2 1783
春和景丽
春和景丽 2020-12-31 04:53

I\'m trying to create a guaranteed lookup for a given enum. As in, there should be exactly one value in the lookup for every key of the enum. I want to guarantee this throug

2条回答
  •  一向
    一向 (楼主)
    2020-12-31 05:13

    enum FunStuff {
      PARTY = "party",
      CAKE = "cake",
      PIZZA = "pizza",
    }
    

    So then if you want all of your Enum values to be required

    type MapOfFunStuff = {
      counts: { [key in FunStuff] : number };
    }
    

    Then if you only want values in your enum but any amount of them you can add ?

    type MapOfFunStuff = {
      counts: { [key in FunStuff]? : number };
    }
    

提交回复
热议问题