Mui*_*rik 2 javascript typescript angular
在我的Angular应用程序中,我有一个过滤功能,可以跟踪用户输入的过滤器值,以及这些过滤器值当前是否已启用/活动.我正在初始化这些过滤器,如下所示:
filters = { language: [], location: [], zipArray: [], firstName: [], lastName: [] };
Run Code Online (Sandbox Code Playgroud)
我在这部分代码中遇到了一个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 = [];
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的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 = [];
}
}
Run Code Online (Sandbox Code Playgroud)
解决方案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;
}
}
Run Code Online (Sandbox Code Playgroud)