I have a nested json like so, which I cannot modify as it is part of some package
const myjson = {
properties: {
'firstname':'david'
},
class: 'primary'
}
I want to add another key value to properties, so that it looks like
const myjson = {
properties: {
'firstname':'david',
'lastname' :'watson'
},
class: 'primary'
}
So I used the following
myjson.properties['lastname'] = 'watson';
This gives the error
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)
I think I have to use as keyof typeof something like below which is wrong syntax and doesn't fix the error
myjson.properties['lastname' as typeof keyof myjson.properties] = 'watson';
Runnable code with the error can be seen here https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwFYXDAvDA3gKBvmABwCcRCBTYqAS3IgC5s8CWByAM2uOjAEM5yreqwAmvAG7URrZvgC+AGlkxgAG14QGMViWpxexBDLk5EKcADoSZSjToBtVup79BMDTCgIKIdjADW5Ai+8MioYFakFFS0EAC6GNoA7rxQ4awA3DigkCCq5BaqIADmABRm4QCUGUA
Edit#1: I made a small error in the order of typeof keyof in the above statement. Now the error is gone. The correct statement is
myjson.properties['lastname' as keyof typeof myjson.properties] = 'watson';
Edit#2: Found one more way to do this without the error
Object.assign(myjson.properties, {'lastname': 'watson'});
properties? Any string or onlyfirstnameandlastname?state,country. Or did you mean the keys could be of another data type?