从 typesctipt 中的数组中过滤非 null

问题描述 投票:0回答:1

我有这个代码:

let x1: (number | null)[] = [null, 1, 2, 3, null];
let x2: number[] = x1.filter( o => o !== null );

我正在尝试使用

filter
过滤非空值。 VS代码给了我这个错误

类型“(number | null)[]”不可分配给类型“number[]”。类型 '数字| null' 不能分配给类型'number'。类型“null”不是 可分配给类型“number”.ts(2322)

提前致谢。

javascript typescript
1个回答
0
投票

数组的

filter()
方法仅在您传递给它的回调函数是返回类型谓词(形式为
arg is Type
)的函数时才会缩小。在 TypeScript 5.4 及更低版本中,您需要手动注释返回类型:

// TS5.4 and below
let x1: (number | null)[] = [null, 1, 2, 3, null];
let x2: number[] = x1.filter((o): o is number => o !== null); // okay

但是从 TypeScript 5.5 开始,将从函数实现中推断出类型谓词,如 microsoft/TypeScript#57465 中实现的那样,这意味着您的代码将突然开始按原样工作:

// TS5.5 and above
let x1: (number | null)[] = [null, 1, 2, 3, null];
let x2: number[] = x1.filter(o => o !== null);

Playground 代码链接

© www.soinside.com 2019 - 2024. All rights reserved.