首页 > 解决方案 > “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[];
}

标签: javascriptreactjstypescriptecmascript-6types

解决方案


好吧,主要的一点是你的累加器没有类型,所以它的变量在编译时acc不应该有属性。country

为什么你得到never?因此:https ://www.tutorialsteacher.com/typescript/typescript-never

首先,您需要以这种方式给它类型:

globalBrands.reduce<NewBrandInterface>(...)

然后你会得到一个错误{},因为默认值,没有所有预期的道具(,,,idlettercountry所以你有两个选择:

  1. 将这些属性设为可选
  2. acc使用所需的所有属性初始化

推荐阅读