TypeScript, --strictNullChecks
模式。
假设我有一个可为空的字符串数组 (string | null)[]
。有什么单表达式的方法可以以这样一种方式删除所有 null,使得结果的类型为 string[]
?
const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;
Array.filter 在这里不起作用:
// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);
数组推导式本来可以使用,但它们在 TypeScript 中不被支持。
实际上,这个问题可以概括为从联合类型的数组中过滤掉具有特定类型的条目。但是,让我们专注于包含 null 和 undefined 的联合类型,因为这些是最常见的用例。
array.filter
的方式非常好。甚至不需要: string[]
,只需这样:const filterdArray = array.filter(x => x != null);
编译器会推断出filterdArray
的类型为string[]
。您使用的 TypeScript 版本是什么? - Nitzan Tomer