gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:24:35 32 4
gpt4 key购买 nike

在下面的代码中,我想不必添加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) => { ... })

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

最佳答案

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

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

如果您需要经常这样做,那么您可以创建一个适用于大多数类型的通用实用程序函数:
const removeNulls = <S>(value: S | undefined): value is S => value != null;

这里有些例子:
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;
});

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

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

查看 TypeScript 的 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[];

所以,关键是 value is S callbackfn 的返回类型,显示为 user-defined type guard .

关于typescript - 用于删除未定义项的过滤器未被 TypeScript 选取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57988567/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com