我有一个对象
const person = {
first: 'John',
last: 'Doe',
id: 1,
}
我想从人员对象中删除键。所以在JavaScript中
['first', 'last'].forEach((i) => {
delete person[i]
})
错误(来自未编译的VSCode编辑器)
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ first: string; last: string; id: number; }'.
No index signature with a parameter of type 'string' was found on type '{ first: string; last: string; id: number; }'.ts(7053)
但是在TypeScript中显示错误。TypeScript中的等效代码是什么。谢谢。
尝试这个:
const keysToDelete: (keyof typeof person)[] = ['first', 'last']
keysToDelete.forEach((i) => {
delete person[i]
})
您需要让TS知道您仅使用的键,person
而不仅仅是任意字符串
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句