typescript - 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,
}
任何帮助表示赞赏。
谢谢。
解决方案
Object.entries(chapter)
return string[]
所以你输入的foreach
只是字符串。所以打字稿会抛出这个错误
所以你在这里有两个选择。将索引类型签名添加到您的界面或重新键入您的密钥:
将索引类型签名添加到您的界面:
export interface Chapter { [key: string]: any; id: string; code: string; number: number; policies: Policy | string; }
阅读有关索引签名的更多信息
重新键入您的密钥:
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
}
}
});
推荐阅读
- conda - 这个命令'conda config --set auto_activate_base False or True'对于linux中的anaconda是什么意思
- visual-studio - 特定场景需要哪个 VC Runtime?
- android - RTL 水平 RecyclerView 在 CoordinatorLayout 的 NestedScrollView 内无法正常工作
- java - Oracle 存储函数与查询中的联接
- python - Python如何从字符串中解析2个URL然后将其映射回来?
- android - 是否可以将 Preview、ImageAnalysis 和 VideoCapture 与 CameraX 结合使用?
- spring - Spring Boot Eureka + Zuul 可以在同一个服务上操作吗
- python - Python:我需要一个单例吗?
- c++ - 在循环中声明变量会花费更多的性能吗?
- ffmpeg - FFMPEG - 使用 rclone mount 在 Gdrive 上将 MKV 转换为 MP4。错误:输出文件 #0 不包含任何流