![](/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.