Typescript 元素隐式地具有一个';任何';因为类型';{}';没有索引签名

Typescript 元素隐式地具有一个';任何';因为类型';{}';没有索引签名,typescript,Typescript,我试图用TypeScript做一个codewars任务,但是我在标题中遇到了错误。我假设问题是我需要定义传递到reduce函数中的对象的类型,但我不知道签名应该是什么 export function duplicateEncode(word: string): string{ const counts = word.split('').reduce((acc, val) => { if (val in acc){ acc[val] += 1;

我试图用TypeScript做一个codewars任务,但是我在标题中遇到了错误。我假设问题是我需要定义传递到reduce函数中的对象的类型,但我不知道签名应该是什么

export function duplicateEncode(word: string): string{
    const counts = word.split('').reduce((acc, val) => {
        if (val in acc){
            acc[val] += 1;
        } else{
            acc[val] = 1;
        }
        return acc;
        }, {})
    return word.split('').map(char => counts[char] == 1 ? '(' : ')').join('');
}

您可以通过定义变量来声明累加器的类型:

导出函数duplicateEncode(字:字符串):字符串{ 常量acc:{[key:string]:number}={}; 常量计数=字分割(“”)。减少((acc,val)=>{ if(acc中的val){ acc[val]+=1; }否则{ acc[val]=1; } 返回acc; },acc); 返回word.split(“”).map(char=>counts[char]==1?'(':')).join(“”); } 类型
{[key:string]:number}
是一个对象,其中键是字符串,值是数字

您还可以断言内联类型:

const counts=word.split('').reduce((acc,val)=>{
...
返回acc;
},{}作为{[key:string]:number});

您可以通过定义变量来声明累加器的类型:

导出函数duplicateEncode(字:字符串):字符串{ 常量acc:{[key:string]:number}={}; 常量计数=字分割(“”)。减少((acc,val)=>{ if(acc中的val){ acc[val]+=1; }否则{ acc[val]=1; } 返回acc; },acc); 返回word.split(“”).map(char=>counts[char]==1?'(':')).join(“”); } 类型
{[key:string]:number}
是一个对象,其中键是字符串,值是数字

您还可以断言内联类型:

const counts=word.split('').reduce((acc,val)=>{
...
返回acc;
},{}作为{[key:string]:number});
您可以使用任何字符串(字符)作为键,因此
{[key:string]:number}
应该执行以下操作:

导出函数duplicateEncode(字:字符串):字符串{ 常量acc:{[key:string]:number}={} 常量计数=字分割(“”)。减少((acc,val)=>{ if(acc中的val){ acc[val]+=1; }否则{ acc[val]=1; } 返回acc; },acc) 返回word.split(“”).map(char=>counts[char]==1?'(':')).join(“”); } 您可以使用任何字符串(字符)作为键,因此
{[key:string]:number}
应该执行以下操作:

导出函数duplicateEncode(字:字符串):字符串{ 常量acc:{[key:string]:number}={} 常量计数=字分割(“”)。减少((acc,val)=>{ if(acc中的val){ acc[val]+=1; }否则{ acc[val]=1; } 返回acc; },acc) 返回word.split(“”).map(char=>counts[char]==1?'(':')).join(“”); }