首页 文章

TypeScript过滤掉数组中的空值

提问于
浏览
23

TypeScript, - strictNullChecks模式 .

假设我有一个可以为空的字符串数组(字符串| null)[] . 什么是 single-expression 方法以一种结果具有类型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和未定义的联合,因为这些是最常见的用例 .

4 回答

  • 46

    您可以在 .filter 中使用type predicate函数以避免选择退出严格类型检查:

    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[]>(...) .

  • 17

    与@ bijou-trouvaille的答案类似,您只需将 <arg> is <Type> 声明为过滤函数的输出:

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

    您可以将 filter 结果转换为所需的类型:

    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[];
    

    code in playground

  • 10

    我相信你一切都很好,除了类型检查只是使过滤类型与返回类型不同 .

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

相关问题