Types from both keys and values of object in Typescript

后端 未结 3 1162
执笔经年
执笔经年 2020-12-28 13:32

I have two sets of string values that I want to map from one to the other as a constant object. I want to generate two types from that mapping: one for keys and one for val

3条回答
  •  伪装坚强ぢ
    2020-12-28 13:53

    You are trying to infer the type from the object (which can have any number of keys/values). You can try to describe the type (or maybe better an interface) first and then infer Kyes and Values like so:

    type KeyToObjMap = {
      some: "other",
      more: "somemore",
    };
    
    type Keys = keyof KeyToObjMap;
    
    type Values = KeyToObjMap[Keys];
    
    let one: Values = "some";
    let two: Values = "other";
    let three: Keys = "some";
    let four: Values = "somemore";
    let five: Keys = "fun";
    

    And you will have a correct highlight in IDE.

提交回复
热议问题