Warm tip: This article is reproduced from serverfault.com, please click

Extending Angular DatePipe errors in Angular 11, worked in Angular 10

发布于 2020-11-12 14:45:08

Originally, I had a simple extension to the DatePipe to transform a date value from our standard (YYYYMMDD format) so that the DatePipe in Angular could then use it.

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);
}

There is some additional checking in the class for proper formats, etc., but the basics of the issue are there. This worked in Angular 10. I just updated to Angular 11, and the code now produces an error on the transform:

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'.
Questioner
Steven Scott
Viewed
0
yurzui 2020-11-12 23:34:34

Angular 11 brings stricter types for DatePipe where method overloading is used.

You can calm down TypeScript compiler by adding overload for transform method like:

transform(DateValue: null | undefined, args?: string): null;
transform(DateValue: number, args: string): string | null {
  ...
}