带有 Typescript 的 Momentjs:“类型字符串不可分配给类型‘日期’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44033071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Momentjs with Typescript : "type string is not assignable to type 'Date'"
提问by undefined
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? Should not this return Date
为什么 getCurrentTime 返回 String?应该不是这个返回日期
回答by basarat
“type string is not assignable to type 'Date'”
“类型字符串不能分配给类型'日期'”
lastUpdated = Date
should be lastUpdated: string
.
lastUpdated = Date
应该是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');
}
}
回答by Dr NVS
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');
}
}