TypeScript,——strictNullChecks模式。

假设我有一个可空字符串数组(string | null)[]。什么是单表达式的方式,以这样的方式删除所有的空值,结果有类型字符串[]?

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;

数组中。过滤器在这里不起作用:

// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);

数组推导式可以工作,但TypeScript不支持。

实际上,这个问题可以推广为通过从联合中删除具有特定类型的项来过滤任何联合类型的数组的问题。但是让我们关注带有null和可能未定义的联合,因为这些是最常见的用例。


当前回答

如果您已经使用了Lodash,您可以使用compact。 或者,如果你喜欢Ramda, Ramda的附属品也有紧凑的功能。

两者都有类型,所以您的tsc会很高兴,并得到正确的类型。

从Lodash d.ts文件:

/**
 * Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are
 * falsey.
 *
 * @param array The array to compact.
 * @return Returns the new array of filtered values.
 */
compact<T>(array: List<T | null | undefined | false | "" | 0> | null | undefined): T[];

其他回答

我相信除了类型检查只是让过滤后的类型与返回类型不不同之外,您都做得很好。

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = array.filter(f => f !== undefined && f !== null) as any;
console.log(filterdArray);

下面是一个使用NonNullable的解决方案。我发现它甚至比@ bijouu -trouvaille的公认答案更简洁

function notEmpty<TValue>(value: TValue): value is NonNullable<TValue> {
    return value !== null && value !== undefined;
}
const array: (string | null | undefined)[] = ['foo', 'bar', null, 'zoo', undefined];

const filteredArray: string[] = array.filter(notEmpty);
console.log(filteredArray)
[LOG]: ["foo", "bar", "zoo"]

类似于@ bijouu -trouvaille的回答,你只需要声明<arg> is <Type>作为过滤器函数的输出:

array.filter((x): x is MyType => x !== null);

还有一个很好的措施,因为人们经常忘记flatMap可以一次性处理过滤器和映射(这也不需要任何类型转换字符串[]):

// (string | null)[]
const arr = ["a", null, "b", "c"];
// string[]
const stringsOnly = arr.flatMap(f => f ? [f] : []);

如果您已经使用了Lodash,您可以使用compact。 或者,如果你喜欢Ramda, Ramda的附属品也有紧凑的功能。

两者都有类型,所以您的tsc会很高兴,并得到正确的类型。

从Lodash d.ts文件:

/**
 * Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are
 * falsey.
 *
 * @param array The array to compact.
 * @return Returns the new array of filtered values.
 */
compact<T>(array: List<T | null | undefined | false | "" | 0> | null | undefined): T[];