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和可能未定义的联合,因为这些是最常见的用例。
我已经多次回到这个问题上,希望一些新的Typescript特性或类型可以解决这个问题。
这里有一个简单的技巧,我很喜欢结合map和后续过滤器。
const animals = ['cat', 'dog', 'mouse', 'sheep'];
const notDogAnimals = animals.map(a =>
{
if (a == 'dog')
{
return null!; // just skip dog
}
else {
return { animal: a };
}
}).filter(a => a);
你会看到我返回null!它实际上变成了类型never——这意味着最终的类型没有null。
这与最初的问题略有不同,但我发现自己经常遇到这种情况,这有助于避免另一个方法调用。希望有一天Typescript会提出一个更好的方法。
为了避免每个人都不得不一遍又一遍地编写相同类型的保护helper函数,我将称为isPresent, isDefined和isfill的函数绑定到一个helper库:https://www.npmjs.com/package/ts-is-present
当前类型定义为:
export declare function isPresent<T>(t: T | undefined | null): t is T;
export declare function isDefined<T>(t: T | undefined): t is T;
export declare function isFilled<T>(t: T | null): t is T;
你可以这样使用:
import { isDefined } from 'ts-is-present';
type TestData = {
data: string;
};
const results: Array<TestData | undefined> = [
{ data: 'hello' },
undefined,
{ data: 'world' }
];
const definedResults: Array<TestData> = results.filter(isDefined);
console.log(definedResults);
当Typescript捆绑这个功能时,我将删除这个包。但是,现在,享受吧。