angularjs - Momentjs עם Typescript : "type string אינו ניתן להקצה לסוג 'Date'"


עד עכשיו השתמשתי בספריית momentjs כך:

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'); 
 }
}

הקוד שלמעלה מציג לי את השגיאה הזו: סוג string אינו ניתן להקצאה לסוג 'Date'**

אבל אותו קוד בדיוק עובד היטב כשאני משתמש בשורה הזו במקום בייבוא המודול, אפילו במאגרי מסעדות אחרים

הכרז על משתנה moment: כל;

אבל אני לא יכול להשתמש בהצהרה שלמעלה כפי שהיא משתמשת ב-"var": ו- 'any' אינו מומלץ על ידי Lint.

למה getCurrentTime מחזיר מחרוזת? האם זה לא אמור להחזיר תאריך?

תשובה #1

סוג 'string' לא ניתן להקצות לסוג 'Date'

lastUpdated=Date צריך להיות lastUpdated: string.

קוד

תוקנו גם כמה דברים נוספים:

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'); 
 }
}

תשובה #2

ניתן להימנע מקריאה לפונקציה נוספת על ידי הקוד שלמטה

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');
  }
}