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
Add a ment  | 

2 Answers 2

Reset to default 5

Your 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