typescript将元素添加到对象

时间:2018-01-03 17:05:49

标签: javascript typescript

如何在此对象中添加'Open Street Map': this.LAYER_OSM.layer,(最后)? :

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

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

我尝试:

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

但我有这个错误:

Element implicitly has an 'any' type because type '{ 'Route': TileLayer; 'Satellite': TileLayer; 'Terrain': TileLayer; }' has no index signature.

2 个答案:

答案 0 :(得分:0)

@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;

答案 1 :(得分:0)

正确的方法是添加索引签名:

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

所以你可以做到

 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;