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和可能未定义的联合,因为这些是最常见的用例。


当前回答

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

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

其他回答

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

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

如果您可以接受另一个.map()的开销,一个优雅的解决方案是使用非空断言操作符。

const array = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = array.filter(s => s != null).map(s => s!);

如果你想保留未定义,你可以在变量上使用typeof,并使用实用程序类型Exclude来从类型中删除空值。

const array = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = array
  .filter(s => s !== null)
  .map(s => s as Exclude<typeof s, 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会提出一个更好的方法。

结合上面我最喜欢的答案之一,与一些通用技巧和对Array接口的扩展,我能够做出一个全局定义,添加到您的模块后,允许任何数组被“压扁”,删除所有空值替换(任何|undefined|null)[]与任何[]。

mixedarray . squash()适合链接和映射。

只需在模块的某个地方添加这段代码(可以随意省略eslint的东西,但我的set在这里的一些事情让我感到困扰):

/* eslint-disable no-unused-vars */
/* eslint-disable no-extend-native */
declare global {
  interface Array<T> {
    squish<NonNull, Nullable extends (NonNull | undefined | null)>(): NonNull[];
  }
}

if (!Array.prototype.squish) {
  Array.prototype.squish = function squish<NonNull, T extends(NonNull|undefined|null)>
  (this: T[]): NonNull[] {
    return this.flatMap((e) => (e ? [e] : [])) as NonNull[]
  }
}

刚刚意识到你可以这样做:

const nonNull = array.filter((e): e is Exclude<typeof e, null> => e !== null)

这样你:

得到一行代码,没有附加函数 不需要知道数组元素的类型,所以你可以到处复制!