Types from both keys and values of object in Typescript

后端 未结 3 1161
执笔经年
执笔经年 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 14:00

    I know that it may not be related, but for my usecase, I reached this question because I wanted to create a type based on an object or array. So I just thought it may be useful for someone with the same usecase reaching this question to use enums: You can simply define an enum like this:

    enum Arrow {
      Up,
      Down,
      Left,
      Right
    }
    

    You can read more about them here and here.

    You can now use this enum as a type:

    type Props = {
      arrow: Arrow
    }
    
    const Component = (props: Props) => {
      switch(props.arrow) {
        case Arrow.Up:
          // go-up
        case Arrow.Down:
          // go-down
        ...
      }
    
    }
    

    and you can use it in your components:

      
    

提交回复
热议问题