![](/img/trans.png)
[英]Typescript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
[英]TypeScript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'
我的代码只是警告正常,但是在使用字符串访问 object 中的元素时,我遇到了来自 Ts 的错误类型。
useEffect(() => {
const categoriesResult: CategoryResult[] = Object.values(
questions?.reduce((r, e) => {
const k = e.category.id;
if (!r[k as keyof object])
return r[k].totalCount += 1;
}, {})
);
setCategories(categoriesResult);
}, [questions]);
更具体地说,错误在 r[k] 中。
谢谢
这里发生了很多事情,所以我将逐行解压缩。
首先,让我们忽略 useEffect。
接下来是作业:
const categoriesResult: CategoryResult[] = Object.values(
这看起来不错Object.values
将返回一个数组,并且您希望它们是CategoryResult
类型。
好的,让我们处理整个 reduce 块:
questions?.reduce((r, e) => {
const k = e.category.id;
if (!r[k as keyof object])
return r[k].totalCount += 1;
}, {})
您的一系列问题将简化为 object {}
。
第一个问题,您需要始终返回r
,所以让我们这样编写代码:
questions?.reduce((r, e) => {
const k = e.category.id;
if (!r[k as keyof object]) {
r[k].totalCount += 1;
}
return r
},{})
如果不返回 r,您将不会减少,您将有一个空的 object。
接下来, r
开始它的生命等于{}
- 一个 object - 因此错误 - 字符串不能用于索引类型{}
下面有一些您想要实现的有效代码,在此代码中,明确设置了{}
的类型,以便它知道 object 具有字符串键和 CategoryResult 类型的值:
// The result type
type CategoryResult = {
totalCount: number;
};
// Some example questions
const questions = [
{
category: {
id: "How should this work?",
},
},
{
category: {
id: "Does that make sense?",
},
},
{
category: {
id: "Does that make sense?",
},
},
];
// A count on questions
const questionCounts = questions?.reduce(
(r, e) => {
const k = e.category.id;
if (r[k] === undefined) {
r[k] = {
totalCount: 1,
};
} else {
r[k].totalCount += 1;
}
return r;
},
// The type of the questions count accumulator in the reduce
{} as Record<string, CategoryResult>
);
const categoriesResult: CategoryResult[] = Object.values(questionCounts);
console.info("result", { categoriesResult });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.