angular - 如何在 Angular 中覆盖/匹配扩展的CurrencyPipe方法类型

标签 angular typescript oop angular2-pipe

我正在尝试重用 Angular common 中的现有货币管道。目标是当值取整时截断 .00。为此我写了这段代码:

/** Transform currency string and round it.  */
@Pipe({name: 'customCurrency'})
export class CustomCurrencyPipe extends CurrencyPipe implements PipeTransform {
  transform(value: number|string|null|undefined): string|null {
    if (!isValue(value)) return null;
    const valueFormat = (+value % 1 === 0) ? '1.0-0' : '1.2-2';
    return super.transform(value, 'USD', 'symbol', valueFormat);
  }
}

function isValue(value: number|string|null|undefined): value is number|string {
  return !(value == null || value === '' || value !== value);
}

如果我将转换类型设置为:any,则运行没有问题。但是我不允许在当前环境中使用任何内容。如果我将其设置为 :string|null 我会收到此错误:

TS2416: Property 'transform' in type 'CustomCurrencyPipe' is not assignable to the same property in base type 'CurrencyPipe'.
  Type '(value: string | number | null | undefined) => string | null' is not assignable to type '{ (value: string | number, currencyCode?: string | undefined, display?: string | boolean | undefined, digitsInfo?: string | undefined, locale?: string | undefined): string | null; (value: null | undefined, currencyCode?: string | undefined, display?: string | ... 1 more ... | undefined, digitsInfo?: string | undefin...'.
    Type 'string | null' is not assignable to type 'null'.
      Type 'string' is not assignable to type 'null'.

7   transform(value: number|string|null|undefined): string|null {

如何设置返回类型以使其与扩展管道的签名匹配?

最佳答案

实际上你的代码没有任何问题。 Angular 团队在版本 11 中引入了更严格的类型,其中一些管道存在过载。

来源:https://github.com/angular/angular/pull/37447

因此,这纯粹是一个 typescript 编译器问题。您可以通过简单地实现重载来摆脱它。

@Pipe({ name: 'customCurrency' })
export class CustomCurrencyPipe extends CurrencyPipe implements PipeTransform {
  transform(value: number | string | null | undefined): null;
  transform(value: number | string | null | undefined): string | null {
    if (!isValue(value)) return null;
    const valueFormat = +value % 1 === 0 ? '1.0-0' : '1.2-2';
    return super.transform(value, 'USD', 'symbol', valueFormat);
  }
}

Stackblitz

关于angular - 如何在 Angular 中覆盖/匹配扩展的CurrencyPipe方法类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69226753/

相关文章:

javascript - 与 swiper 结合使用时奇怪的 ngx-translate 行为

javascript - Typescript 自动完成功能在 VSCode 中不起作用

c# - 面向对象编程 : Separation of Data and Behavior

typescript - Angular2 使用值等价或引用相等检测变化?

javascript - 是否可以在不使用 "new"关键字的情况下使用 Javascript 原型(prototype)?

python - 将变量内容转换为代码行

跨多个组件实例的 Angular 2 全局变量

html - 将绝对 div 放在相对 div 下

javascript - 模糊事件未在 IE 中触发 - Angular 2+

angular - TS2339 : Property 'assign' does not exist on type