angularjs - 带有 typescript : "type string is not assignable to type ' Date'"的 Momentjs

标签 angularjs angular typescript

到目前为止,我一直在使用这样的 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'); 
 }
}

上面的代码向我显示了这个错误:该类型字符串不可分配给类型 'Date'**

但是当我使用这一行代替导入模块时,相同的代码完全正常工作,甚至其他餐厅操作系统

declare var moment: any;



但是我不能使用上面的语句,因为它使用的是 "var": 和 'any'
Lint 不建议这样做。

为什么 getCurrentTime 返回 String?应该不是这个返回日期

最佳答案

“type string is not assignable to type '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'); 
 }
}

关于angularjs - 带有 typescript : "type string is not assignable to type ' Date'"的 Momentjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44033071/

相关文章:

javascript - 让 AngularJS 指令在 iframe 中工作

javascript - Angular ui.bootstrap Accordion 和 bootstrap3

angular - typescript:从外部路径导入模块

javascript - 从 JavaScript 访问 TypeScript 函数

javascript - match() 函数输入的 TypeScript "type"是什么

javascript - Angularjs ui-router 无法从状态 'results/0' 解析 'survey'

javascript - 在 JQuery 中从 Angular 调用 ng-attr-id

Angular -> tslint 错误,规则定义 jsdoc/newline-after-description

angular - Angular2 中的条件 ngModel

typescript - 在哪里可以找到稳定的 Office.js TypeScript 定义?