Till now I was using momentjs library like this:
import * as moment from 'moment'; // import moment.
@Component({..});
export class TestClass {
  lastUpdated = Date
  constructor(private myService: MyService){
    this.lastUpdated = this.getCurrentTime(); **// this shows error.. that type string is not assignable to type 'Date'**
  }
 var getCurrentTime(){
    return moment().format('DD MMM YYYY HH:mm:ss'); 
 }
}
Above code shows me this error: that type string is not assignable to type 'Date'**
But same code exactly working fine when I use this line in place of the import module, evenn other resturent os
declare var moment: any;
But I canot use above statement as it is using "var": and 'any' is not suggested by Lint.
Why getCurrentTime is returning String? Should not this return Date
“type string is not assignable to type 'Date'”
lastUpdated = Date should be lastUpdated: string.
Fixed a few other things as well:
import * as moment from 'moment'; // import moment.
@Component({..});
export class TestClass {
  lastUpdated: string;
  constructor(private myService: MyService){
    this.lastUpdated = this.getCurrentTime();
  }
 getCurrentTime(){
    return moment().format('DD MMM YYYY HH:mm:ss'); 
 }
}
                        Can avoid calling one more function by the below code
import * as moment from 'moment'; // import moment.
@Component({..});
export class TestClass {
  lastUpdated: string;
  constructor(private myService: MyService){
    this.lastUpdated = moment(this.lastUpdated).format('DD MMM YYYY HH:mm:ss');
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With