0

How to add 'Open Street Map': this.LAYER_OSM.layer, in this object (att the end)? :

layersControl = {
  baseLayers: {
    'Route': this.LAYER_GStM.layer,
    'Satellite': this.LAYER_GSaM.layer,
    'Terrain': this.LAYER_GTM.layer
  }
};

this.layersControl.baseLayers ...add/push... ??

I try with:

this.layersControl.baseLayers['Open Street Map'] = this.LAYER_GTM.layer;

but I have this error:

Element implicitly has an 'any' type because type '{ 'Route': TileLayer; 'Satellite': TileLayer; 'Terrain': TileLayer; }' has no index signature.
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
  • 1
    The same way you add all the other properties. What's the concrete problem? – JB Nizet Jan 03 '18 at 17:09
  • @JBNizet, I want to add the 4th element dynamically with code – Stéphane GRILLON Jan 03 '18 at 17:12
  • 1
    Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – JB Nizet Jan 03 '18 at 17:14
  • @JBNizet, no same solution, I have a space in 'Open Street Map', is it a problem for me – Stéphane GRILLON Jan 03 '18 at 17:16
  • That is not a problem at all. Read the answers carefully. – JB Nizet Jan 03 '18 at 17:16
  • 3
    The problem you have is not related to adding a property. It's related to not giving a proper type to your object, or to not explicitly type it as `any`. Define it as `layersControl: any = { ...`, and the error should disappear. – JB Nizet Jan 03 '18 at 17:34

2 Answers2

0

Solution find by @JB Nizet:

layersControl: any = {
  baseLayers: {
    'Route': this.LAYER_GStM.layer,
    'Satellite': this.LAYER_GSaM.layer,
    'Terrain': this.LAYER_GTM.layer
  }
};

this.layersControl.baseLayers['Open Street Map'] = this.LAYER_OSM.layer;
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
0

The proper way would be to add the index signature:

 interface ILayersControl  {
  baseLayers: {
   [key: string]: TileLayer
  }
 }

So you can do

 const layersControl: ILayersControl = {
    baseLayers: {
      'Route': this.LAYER_GStM.layer,
      'Satellite': this.LAYER_GSaM.layer,
      'Terrain': this.LAYER_GTM.layer
    }
 };

 layersControl.baseLayers["Open Street Map"] = this.LAYER_OSM.layer;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151