输入'{可见性:字符串; 'line-join':字符串; 'line-cap':字符串; } | { 可见性:字符串; }' 不可分配给类型

Type '{ visibility: string; 'line-join': string; 'line-cap': string; } | { visibility: string; }' is not assignable to type

我在 angular 中使用 mapbox。我尝试 show/hide 使用 mapbox 做一些事情。

所以我有这个组件:

export class ToggleLayersComponent implements OnInit {
  layouts = {
    contours: {
      visibility: 'visible',
      'line-join': 'round',
      'line-cap': 'round',
    },
    museums: {
      visibility: 'visible',
    },
  };

  ngOnInit() {}

  toggleLayer(evt: {value: 'contours' | 'museums'}) {
    this.layouts[evt.value] = {
      ...this.layouts[evt.value],
      visibility: this.layouts[evt.value].visibility === 'visible' ? 'none' : 'visible',
    };
  }
}

但是我得到这个错误:

Type '{ visibility: string; 'line-join': string; 'line-cap': string; } | { visibility: string; }' is not assignable to type '{ visibility: string; 'line-join': string; 'line-cap': string; } & { visibility: string; }'.
  Type '{ visibility: string; }' is not assignable to type '{ visibility: string; 'line-join': string; 'line-cap': string; } & { visibility: string; }'.
    Type '{ visibility: string; }' is missing the following properties from type '{ visibility: string; 'line-join': string;

当然是我先用谷歌搜索了。但是我找不到任何解决方案。

那么如何解决这个问题?

谢谢

所以错误就在这一行:

 this.layouts[evt.value] 

所以我什至不能 运行 Angular:

ERROR in src/app/desktop-dashboard/toggle-layer/toggle-layer.component.ts:63:5 - error TS2322: Type '{ visibility: string; 'line-join': string; 'line-cap': string; } | { visibility: string; }' is not assignable to type '{ visibility: string; 'line-join': string; 'line-cap': string; } & { visibility: string; }'.    
  Type '{ visibility: string; }' is not assignable to type '{ visibility: string; 'line-join': string; 'line-cap': string; } & { visibility: string; }'.      
    Type '{ visibility: string; }' is missing the following properties from type '{ visibility: string; 'line-join': string; 'line-cap': string; }': 'line-join', 'line-cap'

63     this.layouts[evt.value] = {

TypeScript 编译器目前还不够“聪明”。当你这样做时:

this.layouts[evt.value] = {
  ...this.layouts[evt.value]
}

它将evt.value视为类型'contours' | 'museums',并且它不能推断它两次是相同的值,并且两次将是相同的对象。基本上它阻止你做:

this.layouts['contours'] = {
  ...this.layouts['museums']
}

在您的示例中,您可以执行以下操作

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

但我想您不想这样做,因为更改检测可能看不到对象引用已更改。如果这对您来说是个问题,我认为除了欺骗编译器之外别无他法:

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

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