Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Momentjs with Typescript : "type string is not assignable to type 'Date'"

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

like image 815
undefined Avatar asked May 17 '17 19:05

undefined


2 Answers

“type string is not assignable to type 'Date'”

lastUpdated = Date should be lastUpdated: string.

Code

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'); 
 }
}
like image 138
basarat Avatar answered Nov 02 '22 11:11

basarat


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');
  }
}
like image 2
Dr NVS Avatar answered Nov 02 '22 11:11

Dr NVS