Sadeghbayan
Sadeghbayan

Reputation: 1163

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

Based on this Link I also tried to declare Date but didn't work.

interface Date {
    getTime(): number
}

Any idea would be appreciated.

Upvotes: 0

Views: 3981

Answers (2)

Vasim Hayat
Vasim Hayat

Reputation: 929

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;
  }
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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.

Upvotes: 5

Related Questions