Javascript 财产';国家';不存在于类型';绝不';和类型';字符串';can';t用于索引类型';{}';

Javascript 财产';国家';不存在于类型';绝不';和类型';字符串';can';t用于索引类型';{}';,javascript,reactjs,typescript,ecmascript-6,types,Javascript,Reactjs,Typescript,Ecmascript 6,Types,我试图使其可索引的属性是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字母=标

我试图使其可索引的属性是
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字母=标题[0];
acc[字母]=acc[字母]|{id:i++,字母,国家:[]};
acc[letter].country.push({title,content:[…content]});
还有另一个错误:

Property 'country' does not exist on type 'never'.ts(2339)
当我这样做时:

const letter=标题[0]作为acc类型的关键字;
acc[字母]=acc[字母]|{id:i++,字母,国家:[]};
//这是抛出错误的行
acc[letter].country.push({title,content:[…content]});
这就是整个功能:

const sortBrands=():NewBrandInterface[]=>{
设i=1;
const result:NewBrandInterface[]=Object.values(
globalBrands.reduce((acc,{title,content})=>{
常量字母=标题[0]作为acc类型的键;
acc[字母]=acc[字母]|{id:i++,字母,国家:[]};
acc[letter].country.push({title,content:[…content]});
返回acc;
}, {}));
返回mergeObjectsInUnique(结果为“字母”);
};
这些是我的界面:

带有URL的接口扩展了各种内容{
url:string;
}
接口国{
标题:字符串;
内容:带URL[];
}
接口NewBrandInterface{
id:编号;
字母:字符串;
国家:国家[];
}

主要的一点是,累加器没有类型,因此
acc
变量在编译时不应该有
country
属性

为什么你从未得到过
?因此:

首先,您需要以以下方式为其指定类型:

globalBrands.reduce<NewBrandInterface>(...)
globalBrands.reduce(…)
然后您将得到一个错误,因为默认值
{}
,没有预期的所有道具(
id
字母
国家
),所以您有两个选项:

  • 将这些属性设置为可选
  • 使用所需的所有属性初始化
    acc

  • 您在编译时得到了错误,对吗?嘿@EmanueleScarabattoli只要我做了这些事情,IDE就会将其标记为错误。第二个错误原因是:如果
    字母
    只能是
    id
    字母
    国家
    ,那么
    acc[字母]
    将始终可用,因为,想必,
    acc
    输入正确。因此语句
    acc[letter]=acc[letter]
    试图将
    acc.letter
    设置为字符串
    letter
    。然后您尝试访问
    country
    属性,如下所示:
    acc.letter.country
    -country不存在。@RandyCasburn有什么解决方案吗?我想首先要了解您正在处理的数据结构。作为一个局外人,问题中没有足够的信息来确定这一点。您的作业都很混乱,您刚刚开始发现代码中的问题。是
    globalBrands.reduce(…)
    还是
    globalBrands.reduce(…)
    ?我将所有属性都设置为可选,现在我得到了这样的结果:
    元素隐式地具有“any”类型,因为类型为“string”的表达式不能用于索引类型为“NewBrandInterface”。在“NewBrandInterface”类型上找不到具有“string”类型参数的索引签名。ts(7053)
    在这种情况下,这可能会有所帮助。我如何将其应用于我的情况?不确定,但。。。如果这样做会发生什么:
    常量字母:“id”|“letter”|“country”
    类型“string”不可分配给类型“id”|“letter”|“country”。ts(2322)