首页 > 解决方案 > Typescript - 为什么我不能使用回调中的键来引用对象

问题描述

为什么我会收到Element implicitly have any type because the expression of type string can't be used to index type Chapter以下代码错误?我不完全明白它在说什么。

我想要的是使用key来自回调的更新特定值:

let chaptersWithStrings = props.chapters;
        chaptersWithStrings.forEach((chapter)  => {

            Object.entries(chapter).forEach(([key, value]) => {
                if (typeof value === 'object') {
                    chapter[key] = JSON.stringify(value)
                }
            })

});

和章节界面

export interface Chapter {
    id: string,
    code: string,
    number: number,
    policies: Policy | string,
}

任何帮助表示赞赏。

谢谢。

标签: typescript

解决方案


Object.entries(chapter)

return string[]

所以你输入的foreach只是字符串。所以打字稿会抛出这个错误

所以你在这里有两个选择。将索引类型签名添加到您的界面或重新键入您的密钥:

  1. 将索引类型签名添加到您的界面:

    export interface Chapter {
        [key: string]: any;
        id: string;
        code: string;
        number: number;
        policies: Policy | string;
    }
    

阅读有关索引签名的更多信息

  1. 重新键入您的密钥:

    Object.entries(chapter).forEach(([key, value]) => {
       const objectKey = key as keyof typeof chapter;            
       if (typeof value === 'object') {
           chapter[objectKey] = JSON.stringify(value)
       }
    })
    

为什么object.keys会返回 string[] 而不是inferer keyof object type?好吧,这就是答案

根据评论编辑:

export interface IChapter {
  id: string;
  code: string;
  number: number;
}

const chapter: IChapter = {
  id: '',
  code: '',
  number: 1,
};

Object.entries(chapter).forEach(([key, value]) => {
  const objectKey = key as keyof typeof chapter;
  if (typeof value === 'object') {
    switch (objectKey) {
      case 'id':
      case 'code':
        chapter[objectKey] = JSON.stringify(value);
        break;
      case 'number':
        chapter[objectKey] = 0; // ! ! here has to be number not JSON.stringify(value) since this is string and you can not assign string to type number
    }
  }
});

推荐阅读