The TypeScript compiler is not “smart” enough at this point. When you do:

this.layouts[evt.value] = {

It sees the evt.value as type 'contours' | 'museums', and it cannot infer that it twice is the same value, and twice will be the same object. Basically it’s preventing you from doing:

this.layouts['contours'] = {

In your example, you can do the following

this.layouts[evt.value].visibility = this.layouts[evt.value].visibility === 'visible'
  ? 'none'
  : 'visible';

But I suppose you do not want to do it this way, because change detection might not see that the object reference has changed. If that’s an issue for you, I see no other way than to trick the compiler:

toggleLayer(evt: {value: 'contours' | 'museums'}) {
  const key = evt.value as 'contours';

  this.layouts[key] = {
    visibility: this.layouts[key].visibility === 'visible' ? 'none' : 'visible'

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top