You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中重写并匹配扩展CurrencyPipe的transform方法类型

自定义CurrencyPipe类型不匹配问题解决方案

报错原因

Angular 内置的 CurrencyPipe 采用函数重载定义 transform 方法的签名,对不同入参的返回类型有严格约束:

  • 入参 value 为 string | number 时,返回类型为 string | null
  • 入参 value 为 null | undefined 时,返回类型固定为 null
    你当前只定义了单个返回类型 string|null,无法匹配第二种重载要求的固定 null 返回类型,因此触发 TS2416 报错。

修复代码

给自定义 transform 方法补充和父类对齐的重载签名即可,原有逻辑不需要改动:

/** Transform currency string and round it.  */
@Pipe({name: 'customCurrency'})
export class CustomCurrencyPipe extends CurrencyPipe implements PipeTransform {
  // 重载1:入参为null/undefined时固定返回null
  override transform(value: null | undefined, currencyCode?: string, display?: string | boolean, digitsInfo?: string, locale?: string): null;
  // 重载2:入参为有效数值时返回string|null
  override transform(value: number | string, currencyCode?: string, display?: string | boolean, digitsInfo?: string, locale?: string): string | null;
  // 方法实现
  override 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) as string|null;
  }
}

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

补充说明

  • override 是Angular 12+ 推荐添加的关键字,用来明确标识方法是重写父类方法,低版本Angular可以移除该关键字。
  • 末尾的 as string|null 是为了消除TS对父类重载返回值的推导歧义,可选添加。

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:24:00