我正試圖重新使用Angular common中現有的貨幣管道。目標是在數值為圓形時將.00截斷。為此,我寫了這段代碼:
/**轉換貨幣字串并取整。 */
@Pipe({name: 'customCurrency'})
export class CustomCurrencyPipe extends CurrencyPipe 實作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'/span>, 'symbol'/span>, valueFormat) 。
}
}
function isValue(value: number|string|null|undefined) :value is number|string {
return !(value == null || value == '' || value != value)。
}
如果我將轉換型別設定為:any,則運行沒有問題。但是在當前的環境中,我不允許使用 any。如果我把它設定為:string|null,我會得到這樣的錯誤:
。span class="hljs-attr">TS2416。屬性 'transform' 在型別'CustomCurrencyPipe'不能分配給同一屬性在基礎型別'CurrencyPipe'。
型別 '(value: string | number | null | undefined) => string | null'不能分配給型別'{(value: string | number, currencyCode? : 字串|未定義, display? : 字串|布林值|未定義, digitsInfo? : 字串|未定義, locale? : 字串|未定義): 字串|null; (value: null|未定義, currencyCode? : 字串|未定義, display? : 字串|... 1 more ... ......。
Type 'string | null'不能被分配到型別'null'。
型別 'string'不可分配給型別'null'。
7 transform(value: number|string|null|undefined): string|null {
我如何設定我的回傳型別,使其與擴展管道的簽名相匹配?
uj5u.com熱心網友回復:
事實上,你的代碼沒有任何問題。Angular團隊在11版本中引入了更嚴格的型別,其中一些管道有多載。
來源。https://github.com/angular/angular/pull/37447
因此,這純粹是一個typescript編譯器的問題。你可以通過簡單地實作多載來擺脫它。
@Pipe({ name: 'customCurrency' })
export class CustomCurrencyPipe extends CurrencyPipe 實作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'/span>, 'symbol'/span>, valueFormat) 。
}
}
uj5u.com熱心網友回復:
這是真的,因為你已經打破了Liskov的SOLID原則,通過改變擴展類中的契約。相反,你可以注入貨幣管道并將其作為一個服務使用
some-module.ts。
...
providers: [CurrencyPipe]。
....
自定義貨幣
@Pipe({name: 'customCurrency'})
export class CustomCurrencyPipe 實作PipeTransform {
constructor(private currencyPipe: CurrencyPipe) {}。
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 this.currencyPipe。 transform(value, 'USD', 'symbol', valueFormat) 。
}
....
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/329344.html
標籤:
