给嵌套JSON添加键值对时Element implicitly has an 'any'错误的解决方法
问题:给第三方不可修改的嵌套对象添加新属性时的TypeScript类型错误
问题背景
有一个来自第三方包的嵌套对象,无法修改其定义:
const myjson = { properties: { 'firstname':'david' }, class: 'primary' }
需要给properties添加新键值对,最终目标结构如下:
const myjson = { properties: { 'firstname':'david', 'lastname' :'watson' }, class: 'primary' }
尝试过程与错误
直接使用属性赋值时触发TypeScript类型错误:
myjson.properties['lastname'] = 'watson';
错误提示:
Element implicitly has an 'any' type because expression of type "lastname" can't be used to index type '{ firstname: string; }'. Property 'lastname' does not exist on type '{ firstname: string; }'.(7053)
最初尝试用as keyof typeof语法但顺序错误,无法解决问题:
myjson.properties['lastname' as typeof keyof myjson.properties] = 'watson';
可行的解决方法
方法1:修正类型断言的顺序
调整typeof与keyof的顺序后,错误消失,代码可正常运行:
myjson.properties['lastname' as keyof typeof myjson.properties] = 'watson';
方法2:使用Object.assign
另一种无需类型断言的写法,同样可以避免类型错误:
Object.assign(myjson.properties, {'lastname': 'watson'});
内容的提问来源于stack exchange,提问作者ontherocks
相关产品推荐
相关产品推荐

