gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:07:35 25 4
gpt4 key购买 nike

我正在使用带 Angular mapbox。我尝试用 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'
};
}

关于javascript - 输入 '{ visibility: string; ' line-join' : string; 'line-cap' : string; } | { visibility: string; }' is not assignable to type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64591546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com