用于删除未定义项的过滤器未被 TypeScript 选取

use*_*776 4 typescript

在下面的代码中,我想不必undefined为filteredDevice添加类型注释。我认为一个被过滤的设备不应该是未定义的,因为我过滤掉了未定义的设备。

但是如果我删除undefined类型注释,TypeScript 会抱怨Type 'ICouchDBDocument | undefined' is not assignable to type 'ICouchDBDocument'.

devices
.filter((device: ICouchDBDocument | undefined) => Boolean(device)) //should filter away all undefined devices?
.map((filteredDevice: ICouchDBDocument | undefined) => { ... })
Run Code Online (Sandbox Code Playgroud)

如何更改我的代码,以便过滤器对类型注释产生影响?

Sly*_*nal 10

解决方案是传递一个类型保护函数,告诉 TypeScript 您正在过滤掉undefined类型的一部分:

devices
.filter((device): device is ICouchDBDocument => Boolean(device)) //filters away all undefined devices!
.map((filteredDevice) => {
    // yay, `filteredDevice` is not undefined here :)
})
Run Code Online (Sandbox Code Playgroud)

如果您需要经常这样做,那么您可以创建一个适用于大多数类型的通用实用程序函数:

const removeNulls = <S>(value: S | undefined): value is S => value != null;
Run Code Online (Sandbox Code Playgroud)

这里有些例子:

devices
.filter(removeNulls)
.map((filteredDevice) => {
    // filteredDevice is truthy here
});


// Works with arbitrary types:
let maybeNumbers: (number | undefined)[] = [];

maybeNumbers
    .filter(removeNulls)
    .map((num) => {
        return num * 2;
    });
Run Code Online (Sandbox Code Playgroud)

(我没有使用该Boolean函数removeNulls以防人们想将它与number类型一起使用- 否则我们也会不小心过滤掉假0值!)


谢谢,我一直在想同样的事情,但你的问题促使我终于解决了:)

查看 TypeScript's lib.es5.d.ts,该Array.filter函数具有这种类型签名(它实际上在文件中有两个,但这是与您的问题相关的一个):

/**
 * Returns the elements of an array that meet the condition specified in a callback function.
 * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
 * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
 */
filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
Run Code Online (Sandbox Code Playgroud)

所以,这里的关键是value is Scallbackfn的返回类型,这表明它是一个用户定义的类型 guard