javascript - typescript 错误 : Type 'undefined[]' is not assignable to type 'void'

标签 javascript angular typescript

在我的 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/

相关文章:

javascript - 在 knockout viewmodel 页面中手动触发其他 DOM 元素的点击事件

Angular 2 单例服务不适合我

typescript - 构建 typescript 前端库

Typescript Pick<> 类型失败 : Argument of type '"foo "' is not assignable to parameter of type ' Pick<Bar, "foo">'

reactjs - 使用 typescript 在 create-react-app 中加载 sass

javascript - 带有获取实例的 console.log() 在异步函数中停止执行

javascript - 未捕获的类型错误 : scrollIntoView is not a function

javascript - 用javascript保存cookie如何指定域?

Angular Material 自动完成 MatAutocompleteTrigger

查询参数更改时,Angular 路由器导航不会加载页面