javascript - “never”类型上不存在属性“country”,并且类型“string”不能用于索引类型“{}”
问题描述
我试图使可索引的属性是title[0]
,它是一个字符串。
我收到此错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)
当我这样做时:
const letter = title[0];
acc[letter] = acc[letter] || { id: i++, letter, country: [] };
acc[letter].country.push({ title, content: [...content] });
还有另一个错误:
Property 'country' does not exist on type 'never'.ts(2339)
当我这样做时:
const letter = title[0] as keyof typeof acc;
acc[letter] = acc[letter] || { id: i++, letter, country: [] };
// This is the line that throws the error
acc[letter].country.push({ title, content: [...content] });
这是整个功能:
const sortBrands = (): NewBrandInterface[] => {
let i = 1;
const result: NewBrandInterface[] = Object.values(
globalBrands.reduce((acc, { title, content }) => {
const letter = title[0] as keyof typeof acc;
acc[letter] = acc[letter] || { id: i++, letter, country: [] };
acc[letter].country.push({ title, content: [...content] });
return acc;
}, {}));
return mergeObjectsInUnique(result, 'letter');
};
这些是我的界面:
interface WithURL extends VariousContent {
url: string;
}
interface Country {
title: string;
content: WithURL[];
}
interface NewBrandInterface {
id: number;
letter: string;
country: Country[];
}
解决方案
好吧,主要的一点是你的累加器没有类型,所以它的变量在编译时acc
不应该有属性。country
为什么你得到never
?因此:https ://www.tutorialsteacher.com/typescript/typescript-never
首先,您需要以这种方式给它类型:
globalBrands.reduce<NewBrandInterface>(...)
然后你会得到一个错误{}
,因为默认值,没有所有预期的道具(,,,id
)letter
,country
所以你有两个选择:
- 将这些属性设为可选
acc
使用所需的所有属性初始化
推荐阅读
- hybris - 斯巴达克斯店面升级后智能编辑不稳定
- python - Pytorch 通过入口值张量有效地索引重复张量
- php - 在带有 MVC NATIVE 的 PHP 中使用 AJAX
- javascript - 使用数组中的键值对创建对象
- html - API 调用后 HTML 视频不适合 - next.js 和 styled-components
- exchangewebservices - 如何在 Windows 2019 中使用 GACUTIL 安装 Microsoft.Exchange.WebServices.2.2.nupkg
- sql - 如何显示表中的唯一条目?
- loops - Solidity:在合约中循环还是只调用所有值?
- python - 如何在 plotly.express 时间轴中向 y 轴添加更多描述
- python - 编剧怎么能达到'ActionChains(driver).move_to_element(element).click(element).perform()'这样的效果呢?