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
答案 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;
}