在我的 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 错误是:
Type 'undefined[]' is not assignable to type 'void'.
我不明白这里的问题是什么?
最佳答案
您将 onZipcodeEnabledChange
的返回类型声明为 void,这意味着该函数不会返回任何内容。在 if 语句中,您将返回 return this.filters.zipArray = [];
的赋值结果,即 []。
Solution 1
只需删除 return 关键字即可。
public onZipcodeEnabledChange(enabled): void {
this.filters.zipArray = this.getZipcodeArray();
if (!enabled || this.filters.zipArray && this.filters.zipArray[0] === ''){
this.filters.zipArray = [];
}
}
Solution 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;
}
}
关于javascript - typescript 错误 : Type 'undefined[]' is not assignable to type 'void' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49904990/