[英]TypeScript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'
My code is just warning fine, but I'm facing an Error type from Ts while accessing an element in the object using string.我的代码只是警告正常,但是在使用字符串访问 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]);
The error is in r[k] to be more specific.更具体地说,错误在 r[k] 中。
Thanks谢谢
There is a lot going on here so I will unpack this line by line.这里发生了很多事情,所以我将逐行解压缩。
First, let's ignore useEffect.首先,让我们忽略 useEffect。
Next, the assignment:接下来是作业:
const categoriesResult: CategoryResult[] = Object.values(
This looks fine Object.values
will return an array, and you expect those to be CategoryResult
type.这看起来不错
Object.values
将返回一个数组,并且您希望它们是CategoryResult
类型。
Ok, let's tackle the entire reduce block:好的,让我们处理整个 reduce 块:
questions?.reduce((r, e) => {
const k = e.category.id;
if (!r[k as keyof object])
return r[k].totalCount += 1;
}, {})
Your array of questions is to be reduced to an object {}
.您的一系列问题将简化为 object
{}
。
First issue, you need to return r
always, so let's make the code this:第一个问题,您需要始终返回
r
,所以让我们这样编写代码:
questions?.reduce((r, e) => {
const k = e.category.id;
if (!r[k as keyof object]) {
r[k].totalCount += 1;
}
return r
},{})
Without returning r you will not reduce, you will have an empty object.如果不返回 r,您将不会减少,您将有一个空的 object。
Next, r
, starts it's life being equal to {}
- an object - hence the error - string can't be used to index type {}
接下来,
r
开始它的生命等于{}
- 一个 object - 因此错误 - 字符串不能用于索引类型{}
There is some valid code below for what you are trying to achieve, in this code, the type of {}
is set explicitly so that it knows the object has string keys, and values of CategoryResult types:下面有一些您想要实现的有效代码,在此代码中,明确设置了
{}
的类型,以便它知道 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.