N
N
Nikolaj Alyabiev2021-11-21 05:57:35
JavaScript
Nikolaj Alyabiev, 2021-11-21 05:57:35

Error TS2345 when using moment js how to fix?

there is such pipe

import { Pipe, PipeTransform } from '@angular/core'
import * as moment from 'moment'


@Pipe({
    name: 'moment'
})

export class MomentPipe implements PipeTransform {
    transform(momentObj: moment.Moment, format: string ="MMMM YYYY"): string {
        return momentObj.format(format)
    }

}


and html component

<p>

    <i class="material-icons" (click)="month(-1)">arrow_left</i>

    <span>
        {{date.date | async | moment}}
    </span>

    <i class="material-icons" (click)="month(1)">arrow_right</i>

</p>


when writing moment in span tag it gives error TS2345: Argument of type 'Moment | null' is not assignable to parameter of type 'Moment'.
Type 'null' is not assignable to type 'Moment'.
How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mukhamed Izudinov, 2021-12-07
@devenji

Adding null through the Union type helped me

export class MomentPipe implements PipeTransform {
    transform(m: moment.Moment | null , format: string = 'MMMM YYYY'): string {
        return m!.format(format)
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question