Home > Mobile >  How do I tell typescript that x key exists in an object
How do I tell typescript that x key exists in an object

Time:06-13

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
    }
  })
})

https://www.typescriptlang.org/play?#code/MYewdgzgLgBBAWBDADgUwjAvAbwFAxgCdVgpEwBzAG3RgC4BtPAggDzoEYAaXfGAXwC6PAqipUAlsgi06MJoUQATCQFcIADToByeGKohtQkTGQgqATwrgMjbBIgAxCWAd6ldAGaIqMobn5eXgB5ACMAKxIoADoAa1QLCAAKBBR0AEpozxBCAFFEYHgUpDQAaQTMAD4YZjgS9AZUsoSYRAx4ixBPGCgLNC66tIhBaIBbFGK0rGragglPSeaLLExMGG0zS2tIbXTZlibUcotoh2dXBFQlLChCVVQ AkCn9ID0oA

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.

  • Related