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


当前回答

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

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

其他回答

我已经多次回到这个问题上,希望一些新的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捆绑这个功能时,我将删除这个包。但是,现在,享受吧。

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

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

你可以将你的筛选结果转换为你想要的类型:

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

这适用于你提到的更一般的用例,例如:

const array2: (string | number)[] = ["str1", 1, "str2", 2];
const onlyStrings = array2.filter(x => typeof x === "string") as string[];
const onlyNumbers = array2.filter(x => typeof x === "number") as number[];

(操场上的代码)

你可以在.filter中使用类型谓词函数来避免选择退出严格的类型检查:

function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
    return value !== null && value !== undefined;
}

const array: (string | null)[] = ['foo', 'bar', null, 'zoo', null];
const filteredArray: string[] = array.filter(notEmpty);

你也可以使用array.reduce<string[]>(…)。

2021年更新:更严格的谓词

虽然这种解决方案适用于大多数场景,但您可以在谓词中进行更严格的类型检查。如前所述,函数notEmpty实际上并不能保证它在编译时正确地识别值是null还是undefined。例如,尝试将其return语句缩短为return value !== null;,您将不会看到编译器错误,即使函数将在undefined上错误地返回true。

缓解这种情况的一种方法是首先使用控制流块约束类型,然后使用一个虚拟变量让编译器进行检查。在下面的例子中,编译器能够推断出value参数在赋值时不能为null或未定义。但是,如果您从if条件中删除|| value === undefined,则会看到编译器错误,通知您上面示例中的错误。

function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
  if (value === null || value === undefined) return false;
  const testDummy: TValue = value;
  return true;
}

提醒一句:在某些情况下,这种方法仍然会失败。一定要注意与逆变相关的问题。