0
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.

Sadeghbayan
  • 1,163
  • 2
  • 18
  • 38

2 Answers2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    @Sadeghbayan FWIW you can remove the need for the explicit constructor if you use [class field initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Field_declarations). – Patrick Roberts Dec 25 '20 at 23:33
  • didn't understand it quietly @PatrickRoberts – Sadeghbayan Dec 25 '20 at 23:41
  • 1
    @Sadeghbayan - He means that if you add `= 0` to your field declarations (`private startTime: number = 0;`, you don't need to write the constructor at all. If you do that, you can also leave off the type, because TypeScript will infer `number` from the initializer: `prvate startTime = 0;`. [In context](https://pastebin.com/9VBsfr7z). – T.J. Crowder Dec 26 '20 at 08:58
1

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;
  }
}
Vasim Hayat
  • 909
  • 11
  • 16
  • @ Vasim - FYI, [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) gives you the same value `new Date().getTime()` does, but more concisely and without an extra object allocation. – T.J. Crowder Dec 26 '20 at 09:06