7

最初,我对 DatePipe 进行了简单的扩展,以从我们的标准(YYYYMMDD 格式)转换日期值,以便 Angular 中的 DatePipe 可以使用它。

export class SlsDatePipe extends DatePipe implements PipeTransform {
    constructor(Locale:string) {
        super(Locale);
    }

    /**
     * Convert the data from the numeric YYYYMMDD to the Javascript date format
     * @param DateValue SLS Formatted number in the YYYYMMDD style
     * @param args Angular Date Pipe args to control the output format
     * @returns Text output following the Javascript date() formats
     */
    public transform(DateValue:number, args:string):string | null {
    
        const DateString:string = DateValue.toString();
        const Year:number  = parseInt(DateString.substr(0, 4), 10);
        const Month:number = parseInt(DateString.substr(4, 2), 10) - 1;
        const Day:number   = parseInt(DateString.substr(6, 2), 10);
        const DateObject:Date = new Date(Year, Month, Day);

        return super.transform(DateObject, args);
}

在类中有一些额外的检查以确保正确的格式等,但问题的基础已经存在。这在 Angular 10 中有效。我刚刚更新到 Angular 11,代码现在在转换时产生错误:

error TS2416: Property 'transform' in type 'SlsTimePipe' is not assignable to the same property in base type 'DatePipe'.
    Type '(TimeValue: number, args: string) => string' is not assignable to type '{ (value: string | number | Date, format?: string, timezone?: string, locale?: string): string; (value: null,
    format?: string, timezone?: string, locale?: string): null; (value: string | number | Date, for mat?: string, timezone?: string, locale?: string): string; }'.
    Type 'string' is not assignable to type 'null'.
4

2 回答 2

6

Angular 11 为使用方法重载的 DatePipe 带来了更严格的类型。

transform您可以通过为以下方法添加重载来让 TypeScript 编译器平静下来:

transform(DateValue: null | undefined, args?: string): null;
transform(DateValue: number, args: string): string | null {
  ...
}
于 2020-11-12T15:34:34.163 回答
4

Yurzui的回答对我不起作用。经过一段时间的斗争后,我决定告诉 TypeScript 放弃任何:

transform(value: string | number | Date, timezone: string = null): any {
    return super.transform(value, DATE_FORMATTING_STRING, timezone);
}
于 2020-12-04T01:17:37.410 回答