首页 前端知识 在 Typescript 中使用 Array.filter(Boolean)

在 Typescript 中使用 Array.filter(Boolean)

2024-06-25 23:06:49 前端知识 前端哥 32 747 我要收藏

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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13541.html
标签
评论
发布的文章

jQuery 选择器

2024-05-12 00:05:34

Vue中public/assets目录区别

2024-07-02 23:07:29

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!