首页 文章

打字稿错误:类型'undefined[]'不能分配给类型'void'

提问于
浏览
2

在我的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'类型 .

我不明白这里的问题是什么?

1 回答

  • 7

    您将 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;
        }
    }
    

相关问题