【发布时间】:2021-11-12 12:40:48
【问题描述】:
我正在尝试重用来自 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 typescript oop angular2-pipe