admin管理员组文章数量:1430185
class SW {
private startTime: number | Date
private endTime: number | Date
constructor() {
this.startTime = 0,
this.endTime = 0
}
start() {
this.startTime = new Date();
}
stop() {
this.endTime = new Date();
}
getDuration() {
const seconds = (this.endTime.getTime() - this.startTime.getTime()) / 1000;
}
}
Now I have this error: Property 'getTime' does not exist on type 'number | Date'.
Based on this Link I also tried to declare Date but didn't work.
interface Date {
getTime(): number
}
Any idea would be appreciated.
class SW {
private startTime: number | Date
private endTime: number | Date
constructor() {
this.startTime = 0,
this.endTime = 0
}
start() {
this.startTime = new Date();
}
stop() {
this.endTime = new Date();
}
getDuration() {
const seconds = (this.endTime.getTime() - this.startTime.getTime()) / 1000;
}
}
Now I have this error: Property 'getTime' does not exist on type 'number | Date'.
Based on this Link I also tried to declare Date but didn't work.
interface Date {
getTime(): number
}
Any idea would be appreciated.
Share Improve this question asked Dec 25, 2020 at 23:18 SadeghbayanSadeghbayan 1,1632 gold badges19 silver badges38 bronze badges 2- FWIW, I remend consistently using semicolons, or relying on automatic semicolon insertion, but not a mix of the two. – T.J. Crowder Commented Dec 25, 2020 at 23:24
- thanks, I will follow that – Sadeghbayan Commented Dec 25, 2020 at 23:28
2 Answers
Reset to default 5Your property is declared as number | Date
, meaning it could be either. In your constructor, it's a number. Later, when you call start
, you change it from number
to Date
. In getDuration
, TypeScript has no way of knowing what it is (number
or Date
).
From looking at your code, you may want to always use number
by using Date.now()
instead of new Date()
and then not using getTime
:
class SW {
private startTime: number;
private endTime: number;
constructor() {
this.startTime = 0,
this.endTime = 0
}
start() {
this.startTime = Date.now();
}
stop() {
this.endTime = Date.now();
}
getDuration() {
const seconds = (this.endTime - this.startTime) / 1000;
}
}
You might also consider having getDuration
either throw an error or return NaN
when this.endTime
or this.startTime
is 0
.
Just make it simple
class SW {
private startTime: number;
private endTime: number;
start() {
this.startTime = new Date().getTime();
}
stop() {
this.endTime = new Date().getTime();
}
getDuration() {
return (this.endTime - this.startTime) / 1000;
}
}
本文标签: javascriptProperty 39getTime39 does not exist on type 39numberDate39Stack Overflow
版权声明:本文标题:javascript - Property 'getTime' does not exist on type 'number | Date' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745441191a2658455.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论