升级Angular 11后扩展DecimalPipe出现类型不匹配报错如何解决
解决方案
报错根因
Angular 11对DecimalPipe的transform方法新增了多重函数重载定义,你现有自定义管道的transform方法参数列表、返回值签名没有完全匹配父类的所有重载规则,触发了TypeScript类型校验不通过,不需要修改Angular内置源码即可解决。
方案1:补全重载签名,匹配父类类型定义
在自定义管道中补全父类的重载签名,同时透传父类要求的可选参数即可解决类型报错,代码示例:
import { DecimalPipe } from '@angular/common'; import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core'; @Pipe({ name: 'customNumberFormat' }) export class CustomNumberFormatPipe extends DecimalPipe implements PipeTransform { // 补全父类三个重载签名 override transform(value: null | undefined, digitsInfo?: string, locale?: string): null; override transform(value: number | string, digitsInfo?: string, locale?: string): string | null; override transform(value: number | string | null | undefined, digitsInfo?: string, locale?: string): string | null { if (!value) { return null; } const processedValue = value.toString().replace(/,/g, ''); // 透传可选参数给父类方法 return super.transform(processedValue, digitsInfo, locale); } // 补全构造函数,注入父类依赖的LOCALE_ID constructor(@Inject(LOCALE_ID) locale: string) { super(locale); } }
说明:override关键字用于明确标记方法为重写父类方法,TS 4.3及以上版本支持,刚好匹配Angular 11对应的TypeScript版本要求。
方案2:用组合代替继承(更推荐)
组合优于继承是Angular自定义扩展内置能力的最佳实践之一,你可以直接实例化DecimalPipe调用其能力,不需要继承父类,从根源上规避类型兼容问题:
import { DecimalPipe } from '@angular/common'; import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core'; @Pipe({ name: 'customNumberFormat' }) export class CustomNumberFormatPipe implements PipeTransform { private readonly decimalPipe: DecimalPipe; constructor(@Inject(LOCALE_ID) locale: string) { this.decimalPipe = new DecimalPipe(locale); } transform(value: number | string | null | undefined, digitsInfo?: string, locale?: string): string | null { if (!value) { return null; } const processedValue = value.toString().replace(/,/g, ''); return this.decimalPipe.transform(processedValue, digitsInfo, locale); } }
说明:该方案解除了和DecimalPipe内部定义的强绑定,后续Angular版本升级时需要调整的代码量更少,也不会出现父类方法变更带来的继承兼容问题。
应急临时方案
如果仅需要快速解决编译报错,不需要长期维护,可以给重写的transform方法加上// @ts-ignore注释忽略类型校验,或者将返回值强转为any,但该方案会丢失类型保护,不建议长期使用。
内容的提问来源于stack exchange,提问作者TrevorGoodchild
相关产品推荐
相关产品推荐

