代码之家  ›  专栏  ›  技术社区  ›  Umbrella

如何从typescript中的对象键字符串中提取精确的并集类型?

  •  -1
  • Umbrella  · 技术社区  · 7 年前

    我有个这样的东西

    const MY_OBJECT = {
      'key': 'key val',
      'anotherKey': 'anotherKey val',
    };
    

    有办法从这个对象中提取 'key' | 'anotherKey'

    2 回复  |  直到 7 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    7 年前

    要获取一个类型,该类型是您需要使用的变量的联合键 keyof typeof variableName .

    const MY_OBJECT = {
        'key': 'key val',
        'anotherKey': 'anotherKey val',
    };
    type MY_OBJECT_KEYS = keyof typeof MY_OBJECT // "key" | "anotherKey"
    
        2
  •  0
  •   Plastic    7 年前

    const MY_OBJECT = {
      key: 'key val',
      anotherKey: 'anotherKey val',
    };
    console.log(keyof MY_OBJECT); // "key" | "anotherKey"