[英]TypeScript type comparison Type 'Site | Site[]' is not assignable to type 'Site'
I have the following interfaces我有以下接口
export interface Site {
id: number;
path: string;
siteLink: string;
features: Feature[];
}
export interface SiteResponse {
data: Site | Site[];
meta?: any;
}
That's being used because I may retrieve an object or an array of objects.之所以使用它,是因为我可能会检索一个对象或一组对象。 Depends on API route I call.取决于我调用的 API 路由。
And here is my service's method I try work with这是我尝试使用的服务方法
getSiteById(id: number): Observable<SiteResponse> {
return this.http.get<SiteResponse>(this.API_URL + '/' + id);
}
And it's subscription这是订阅
this.ss.getSiteById(this.id).subscribe((x: SiteResponse) => {
const site: Site = x.data;
this.link.setValue(site.siteLink);
this.imagePreview = site.path;
site.features.forEach(feature => {
this.features.push(this.fb.control(feature, Validators.required));
});
this.isPending = false;
});
For me it looks OK, but not for the validator.对我来说它看起来不错,但对验证器来说不是。
error TS2322: Type 'Site |错误 TS2322:键入“站点 | Site[]' is not assignable to type 'Site'. Site[]' 不可分配到类型 'Site'。 Type 'Site[]' is not assignable to type 'Site'.类型 'Site[]' 不能分配给类型 'Site'。 Property 'id' is missing in type 'Site[]'. “Site[]”类型中缺少属性“id”。
通过添加额外的类型声明const site: Site = <Site>x.data;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.