Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string' is not assignable to type 'Moment' error

I have an object like this:

import { Moment } from 'moment';

export interface INewsletter {
    id?: number;
    creationDate?: Moment;
    email?: string;
}

export class Newsletter implements INewsletter {
    constructor(public id?: number, public creationDate?: Moment, public email?: string) {}
}

In one place I need to get the date from the form I'm using, but in the second case that is giving me the problem, I just need to get the date from the system and use it in the new created object (without the error, that I do not understand since the date is also a moment).

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';

import { INewsletter } from 'app/shared/model/newsletter.model';
import { NewsletterService } from '../../entities/newsletter/newsletter.service';

@Component({
    selector: 'jhi-footer',
    templateUrl: './footer.component.html'
})
export class FooterComponent implements OnInit {
    newsletter: INewsletter;
    isSaving: boolean;
    creationDate: string;

    constructor(private newsletterService: NewsletterService, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.creationDate = moment().format(DATE_TIME_FORMAT);
        this.newsletter = new Object(); 
(1)     this.newsletter.creationDate = moment().format(this.creationDate); 
(2)     this.newsletter.creationDate = this.creationDate;
    }

So, in both cases (1) and (2) I can not make it work and I do not understand why.

like image 380
Mike Avatar asked Sep 06 '25 09:09

Mike


1 Answers

In both cases, you try to assign a string to Newsletter.creationDate, which expects a Moment object.

Case (1) could work by replacing moment().format(this.creationDate); by moment(this.creationDate); as the .format() method from moment returns a string, as mentionned by @Julien Metral

like image 90
Leo Avatar answered Sep 09 '25 03:09

Leo