[英]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.