为什么我的以下代码出现错误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,
}
任何帮助表示赞赏。
谢谢。
答案 0 :(得分:2)
Object.entries(chapter)
return string[]
所以您在foreach
中输入的只是字符串。所以打字稿会抛出这个错误
因此,您在这里有2个选项。将索引类型签名添加到您的界面或重新键入密钥:
向您的界面添加索引类型签名:
export interface Chapter {
[key: string]: any;
id: string;
code: string;
number: number;
policies: Policy | string;
}
详细了解index signature
重新输入密钥:
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
? here is the answer
根据评论进行编辑:
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
}
}
});
答案 1 :(得分:0)
下面的代码片段将为您提供帮助。
Object.keys(chapter).forEach((key: string) => {
if (chapter[key] !== null && typeof chapter[key]=== 'object') {
chapter[key] = ...; // update the specific value using the key
}
});