【问题标题】:How to use enum values to index an object?如何使用枚举值来索引对象?
【发布时间】:2020-06-18 17:18:38
【问题描述】:

我有一个使用 enum 值作为键的对象。我想迭代那些 enum 值并使用它们来索引所述对象:

enum Foods {
  bread = "bread",
  meat = "meat",
}

type ShoppingList = {
  [Foods.bread]: string;
  [Foods.meat]: string;
};

const shoppingList: ShoppingList = {
  bread: "1 loaf",
  meat: "2 lbs",
};

Object.keys(Foods).forEach((item) => {
  console.log(shoppingList[item]);
});

此确实使用 tsc 构建,但 ts-node 和 VS Code 都在报告:

error TS7053: Element implicitly has an 'any' type because expression of type
  'string'  can't be used to index type 'ShoppingList'. No index signature with
  a parameter of type 'string' was found on type 'ShoppingList'.

17   console.log(shoppingList[item]);
                 ~~~~~~~~~~~~~~~~~~

可以理解,因为Object.keys 返回string[]。但是,您和我都知道,这些字符串仅是Foods 的成员。因为ShoppingList只有使用Foods作为它的键,我们应该能够使用Object.keys的任何成员来索引shoppingList。

这在概念上是有道理的,但我如何将它传达给 TypeScript?

编辑:Foods 和 ShoppingList 需要坚持这两个值,即这里没有动态键。

【问题讨论】:

    标签: javascript typescript enums


    【解决方案1】:

    您不能只使用enum。

    您当然可以只使用强制转换来告诉 TS item 的类型是什么:

    console.log(shoppingList[item as Foods]);
    

    但是每次你需要转换Foods时写起来会很累。

    另一种选择是声明一个明确定义的数组:

    enum Foods {
      bread = "bread",
      meat = "meat",
    }
    
    const FoodsArray = [Foods.bread, Foods.meat];
    
    // Optional: use [key in Foods] to consolidate type definition
    type ShoppingList = {
      [key in Foods]: string;
    };
    
    const shoppingList: ShoppingList = {
      bread: "1 loaf",
      meat: "2 lbs",
    };
    
    FoodsArray.forEach((item) => {
      console.log(shoppingList[item]);
    });
    

    必须手动声明和更新数组是不是有点多余?是的。但据我所知,没有办法直接从enum 推断出准确的类型。

    https://www.typescriptlang.org/play/index.html?ssl=17&ssc=4&pln=1&pc=1#code/KYOwrgtgBAYg9nAJgZygbwFBSgIwE7ACGiUAvFAET5GIUA0WUERALmZc4S-RgL4YYAxnBDI28JMgCCePIQCe7ANoSUAOmrE6sBOs4sAugG4BLeQAdgUAMoALOOfMBLEAHMAMk7HtM2JQGtgRRcdSQMALigxPBdXE14TIRFvZHtHWM8xSLsHZzdMtnJfXAJiSIoARigAGzhCADMebH1ygCYanGQeBIFVaVkFNXq4PABRQkFbAAoppxZgCABKMgA+dEZhUThq4DVa1ynU3IyvFiU5hYNF+OugA

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2020-04-18
      • 2022-12-05
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      相关资源
      最近更新 更多