[英]Momentjs with Typescript : “type string is not assignable to type 'Date'”
Till now I was using momentjs library like this:到目前为止,我一直在使用这样的 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');
}
}
Above code shows me this error: that type string is not assignable to type 'Date'**上面的代码向我显示了这个错误:该类型字符串不可分配给类型 '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;声明 var 时刻:任何;
But I canot use above statement as it is using "var": and 'any' is not suggested by Lint.但是我不能使用上面的语句,因为它使用的是“var”:并且 Lint 不建议使用“any”。
Why getCurrentTime is returning String?为什么 getCurrentTime 返回 String? Should not this return Date应该不是这个返回日期
“type string is not assignable to type 'Date'” “类型字符串不能分配给类型'日期'”
lastUpdated = Date
should be lastUpdated: string
. lastUpdated = Date
应该是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');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.