基于类型的嵌套对象的索引类型

时间:2020-09-23 15:19:58

标签: reactjs typescript

SO上已经有一些有关此主题的答案,但它们似乎都已过时。我想根据给定的类型选择一个组件。我更喜欢使用typeof自动生成对象的类型。声明Comp组件类型的正确方法是什么?

const icons = {
  default: {
    coffee: IconCoffee,
  },
  service: {
    coffee: IconCoffeeService,
  },
} as const;


const Comp = icons[iconSet][iconName];

当前,出现以下错误:type 'string' can't be used to index type

1 个答案:

答案 0 :(得分:0)

在默认情况下,对象文字的类型是所编码的确切对象类型,而不是字典,或者是TS称之为a Record type的类型。要使用任意字符串索引到对象文字中,我们需要将其类型显式声明为记录,在这种情况下为嵌套记录:

int findFrequency(std::vector<int>& v, int x) {

    auto func = [&] (int i) {       // [&] means 'capture by reference'
        if (i == x) return 1;
        else return 0;
    };

    int res = std::count_if(v.begin(), v.end(), func);

    return res;
}
相关问题