在 Typescript 中使用 Array.filter(Boolean)

https://www.karltarvas.com/2021/03/11/typescript-array-filter-boolean.html

012832565eb89d259ba2dee7332164aa.png

对于 Array.filter(Boolean) 这种过滤数组的方法,Typescript 却并没有天然地支持它。《a lot of history to this issue》(https://github.com/microsoft/TypeScript/issues/16655) 帖子中提及了这个问题,且至今没有被完全修复。

在下面的代码片段中,filter 后的返回值 理应string[],但实际得到的却是 (string | null | undefined)[]

const foo: (string | null | undefined)[] = [];
const bar: string[] = foo.filter(Boolean);
//    ^^^
// Type '(string | null | undefined)[]' is not assignable to type 'string[]'.

要修正该问题,可以为 Array.prototype.filter() 增加一个 TS overload,以应对用布尔值构造函数作为过滤函数时的特殊情况。将下列代码保存为 lib.es5.d.ts:

/**
 * Fixes https://github.com/microsoft/TypeScript/issues/16655 for `Array.prototype.filter()`
 * For example, using the fix the type of `bar` is `string[]` in the below snippet as it should be.
 *
 *  const foo: (string | null | undefined)[] = [];
 *  const bar = foo.filter(Boolean);
 *
 * For related definitions, see https://github.com/microsoft/TypeScript/blob/master/src/lib/es5.d.ts
 *
 * Original licenses apply, see
 *  - https://github.com/microsoft/TypeScript/blob/master/LICENSE.txt
 *  - https://stackoverflow.com/help/licensing
 */

/** See https://stackoverflow.com/a/51390763/1470607  */
type Falsy = false | 0 | "" | null | undefined;

interface Array<T> {
  /**
   * Returns the elements of an array that meet the condition specified in a callback function.
   * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
   * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
   */
  filter<S extends T>(predicate: BooleanConstructor, thisArg?: any): Exclude<S, Falsy>[];
}

然后将其作为 include 项添加到 tsconfig 配置中即可:

{
  "include": [
    "lib.es5.d.ts"
  ]
}

dc1995f20297ea8535d9532c80c3eacc.pngd8432ae5b72a04a00cf027640413ad67.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值