在 Typescript 中使用 Array.filter(Boolean)

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

在 Typescript 中使用 Array.filter(Boolean)_第1张图片

对于 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 {
  /**
   * 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(predicate: BooleanConstructor, thisArg?: any): Exclude[];
}

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

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

在 Typescript 中使用 Array.filter(Boolean)_第2张图片在 Typescript 中使用 Array.filter(Boolean)_第3张图片

你可能感兴趣的:(typescript,javascript,前端,开发语言,ecmascript)