Angular 管道和 TypeScript 类型保护

Angular Pipe and TypeScript Type Guard

我在 typescript here and here 中读到了类型保护。但是我仍然遇到编译器错误。

Error:(21, 14) TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{ (callbackfn: (value: Foo, index: number, array: Foo...' has no compatible call signatures.

我关注了 类:

Foo.ts

export class Foo {
  expired: boolean;
}

Bar.ts

export class Bar {
  foo: Foo;
}

MyPipe.ts

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'myPipe'
})
export class MyPipe implements PipeTransform {

  transform(items: Foo[] | Bar[], isExpired: Boolean): Foo[] | Bar[] {
    if (!items) {
      return items;
    }

    if (items[0] instanceof Foo) {
      return items.filter((foo: Foo) => {
        return foo.expired == isExpired;
      });
    } else {
      return items.filter((bar: Bar) => {
        return bar.foo.expired == isExpired;
      });
    }
  }
}

问题是,如何使用打字稿在我的 angular 管道中同时为我的参数 "items" 使用联合绑定和类型保护用法?

Typescript 通常不会根据字段的类型来缩小变量的类型(可区分的联合除外)。更具体地说,打字稿不会根据数组索引进行缩小(这是一个已知的限制)

您可以做的最简单的事情是使用类型断言,或者更优雅的解决方案,自定义类型保护:

class Foo { private x: string; expired: boolean }
class Bar { private x: string; foo: Foo }

function isArrayOf<T>(ctor: new (...args: any[]) => T, arr: any): arr is T[] {
    return arr[0] instanceof ctor
}

export class MyPipe {
    transform(items: Foo[] | Bar[], isExpired: Boolean): Foo[] | Bar[] {
        if (!items) {
            return items;
        }

        if (isArrayOf(Foo, items) {
            return items.filter((foo: Foo) => {
                return foo.expired == isExpired;
            });
        } else {
            return items.filter((bar: Bar) => {
                return bar.foo.expired == isExpired;
            });
        }
    }
}

Playground link