Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading