[英]Typescript error: Type 'undefined[]' is not assignable to type 'void'
在我的Angular应用程序中,我有一个过滤功能,可以跟踪用户输入的过滤器值,以及这些过滤器值当前是否已启用/活动。 我正在初始化这些过滤器,如下所示:
filters = { language: [], location: [], zipArray: [], firstName: [], lastName: [] };
我正在使用这段代码遇到一个Typescript错误 - 特别是这一行: return this.filters.zipArray = [];
public onZipcodeEnabledChange(enabled): void {
this.filters.zipArray = this.getZipcodeArray();
if (!enabled || this.filters.zipArray && this.filters.zipArray[0] === ''){
return this.filters.zipArray = [];
}
}
我得到的TypeScript错误是:
类型'undefined []'不能分配给'void'类型。
我不明白这里的问题是什么?
您将onZipcodeEnabledChange
返回类型onZipcodeEnabledChange
为void,这意味着函数不会返回任何内容。 在if语句中,您返回的返回赋值结果为return this.filters.zipArray = [];
即[]。
解决方案1
只需删除return关键字即可。
public onZipcodeEnabledChange(enabled): void {
this.filters.zipArray = this.getZipcodeArray();
if (!enabled || this.filters.zipArray && this.filters.zipArray[0] === ''){
this.filters.zipArray = [];
}
}
解决方案2
如果你想从该函数返回数组,你需要用any[]
替换void。
public onZipcodeEnabledChange(enabled): any[] {
this.filters.zipArray = this.getZipcodeArray();
if (!enabled || this.filters.zipArray && this.filters.zipArray[0] === ''){
this.filters.zipArray = [];
return this.filters.zipArray;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.