Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'.
like image 656
Steven Scott Avatar asked Nov 12 '20 14:11

Steven Scott


2 Answers

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 {
  ...
}
like image 108
yurzui Avatar answered Nov 20 '22 13:11

yurzui


Yurzui's answer didn't work for me. After a fighting with this for a while I decided to tell TypeScript to frig off with any:

transform(value: string | number | Date, timezone: string = null): any {
    return super.transform(value, DATE_FORMATTING_STRING, timezone);
}
like image 28
bobbyg603 Avatar answered Nov 20 '22 13:11

bobbyg603