I am fairly new to typescript and I want to make type assertion that tells typescript that this key exists in an object so that it doesn't complain. I want to tell typescript isFinished key exists in shape object and it does exist. Thanks
const shapes ={
rectangles :[{
x:1,
}],
ellipses : [{radiusX:'hello'}],
polygons :[{isFinished:false}]
}
Object.keys(shapes).forEach(shapeKey=> {
shapes[shapeKey as keyof typeof shapes].map(shape => {
if(shapeKey === 'polygons'){
shapeKey.isFinished =true
}
})
})
CodePudding user response:
Replace your if statement with this:
if("isFinished" in shape){
shape.isFinished =true
}
You are trying to modify the shape, not the shape key. The condition asserts/checks that the object you are changing has that property to change.
Edit: I know the above solves it, but on another note, you can replace your execution code with one line:
shapes.polygons.forEach(shape => { shape.isFinished = true; })
CodePudding user response:
The issue here is that you're trying to access a property from a string. You have a loop on the KEYS of an object, which means that the property shapeKey is a string.
To access the object that you're looking for you need to access it from the initial object which would be shapes[shapekey]
and since the value for this is an array, you will need to access the first element of the array shapes[shapekey][0].isFinished
.
Hope the explanation was clear.