前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在 Typescript 中使用 Array.filter(Boolean)

在 Typescript 中使用 Array.filter(Boolean)

作者头像
江米小枣
发布2023-03-08 20:04:45
6980
发布2023-03-08 20:04:45
举报
文章被收录于专栏:云前端云前端

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

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

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
/**
 * 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 配置中即可:

代码语言:javascript
复制
{
  "include": [
    "lib.es5.d.ts"
  ]
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-02-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 云前端 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档