从并集中删除类型或在array.filter中使用null并集



我有一个变量声明为:

public filter: string | null;

我试着在过滤器数组函数中使用它,它会返回一个错误:

Argument of type 'string | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'

我想,最好是暂时或在当前范围内,从过滤器变量中删除null并集,这样我就可以使用数组函数。或者以任何其他方式。有什么帮助吗?

refined.filter(a => a.toLocaleLowerCase().includes(this.filter => ); //error at "this.filter"

如果在filter === null的情况下运行过滤函数似乎没有意义,对吗?

在这种情况下,您应该对表达式进行条件设置,并返回一个适当的值:

if (filter)
// TypeScript knows that inside your `if` statement, `this.filter` is never null
return refined.filter(a => a.toLocaleLowerCase().includes(this.filter));
return null; // or anything else

你可以把它变成一个三元表达式:

return filter ? refined.filter(a => a.toLocaleLowerCase().includes(this.filter)) : null;

最新更新