[英]Property 'getTime' does not exist on type 'number | Date'
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'.
现在我有这个错误: Property 'getTime' does not exist on type 'number | Date'.
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.任何想法将不胜感激。
Your property is declared as number | Date
您的属性被声明为number | Date
number | Date
, meaning it could be either. number | Date
,这意味着它可能是。 In your constructor, it's a number.在您的构造函数中,它是一个数字。 Later, when you call start
, you change it from number
to Date
.稍后,当您调用start
,您将其从number
更改为Date
。 In getDuration
, TypeScript has no way of knowing what it is ( number
or Date
).在getDuration
中,TypeScript 无法知道它是什么( number
或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
:通过查看您的代码,您可能希望始终使用number
来使用Date.now()
而不是new Date()
然后不使用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
.您也可以考虑让getDuration
在this.endTime
或this.startTime
为0
时抛出错误或返回NaN
。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.