【问题标题】:Angular Pipe and TypeScript Type GuardAngular Pipe 和 TypeScript 类型保护
【发布时间】:2019-01-04 08:17:34
【问题描述】:

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

错误:(21, 14) TS2349: 无法调用类型缺少 来电签名。输入 '{ (callbackfn: (value: Foo, index: number, array: Foo...' 没有兼容的调用签名。

我有以下课程:

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;
      });
    }
  }
}

问题是,如何使用 typescript 在我的角管道中同时实现对参数“items”的联合绑定和类型保护的使用?

【问题讨论】:

    标签: angular typescript angular-pipe


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 2021-01-22
      • 1970-01-01
      • 2020-11-11
      • 2021-12-10
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多