在我的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
为void,这意味着该函数将不返回任何内容。在if语句中,您将返回return this.filters.zipArray = [];
ie []的赋值结果。
解决方案1
只需删除return关键字即可为您服务。
public onZipcodeEnabledChange(enabled): void {
this.filters.zipArray = this.getZipcodeArray();
if (!enabled || this.filters.zipArray && this.filters.zipArray[0] === ''){
this.filters.zipArray = [];
}
}
解决方案2
如果要从该函数返回数组,则需要用替换void any[]
。
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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句