The attribute 'getTime' is not found in the data 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;
    }
}

I'm encountering an issue with the error message:

Property 'getTime' does not exist on type 'number | Date'.

Attempting a solution as suggested in this Link, I have also tried to declare Date, but it didn't solve the problem.

interface Date {
    getTime(): number
}

If you have any ideas, they would be greatly appreciated.

Answer №1

The variable in question is deemed as number | Date, indicating that it could be either data type. Initially, in your constructor, it is set as a number. However, upon calling start, it transitions from being a number to a Date. This transition creates ambiguity for TypeScript in the function getDuration where it cannot definitively determine its type (number or Date).

Upon reviewing your code, a suggestion could be to consistently use number by utilizing Date.now() instead of new Date() and omitting the usage of 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;
    }
}

Additonally, you could consider implementing logic in getDuration to either raise an error or return NaN if this.endTime or this.startTime is set to 0.

Answer №2

Simplify it

class Timer {
  private start: number;
  private end: number;
 
  begin() {
    this.start = new Date().getTime(); 
  }
  finish() {
    this.end = new Date().getTime();
  }

  getElapsedTime() {
    return (this.end - this.start) / 1000;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angularjs still facing the routing issue with the hashtag symbol '#' in the URL

I have recently made changes to my index.html file and updated $locationProvider in my app.js. After clicking on the button, I noticed that it correctly routes me to localhost:20498/register. However, when manually entering this URL, I still encounter a 4 ...

Is there a way to automatically generate additional text fields based on the user's input?

Is there a way to dynamically add multiple text fields for color and choose design based on user input? For instance, if the user enters 5 in the quantity field, how can I replicate the color and choose design fields 5 times? Additionally, how should I st ...

Encountering a persistent Unhandled rejection Error while utilizing NodeJs with Bluebird library

Currently in the process of developing a daemon that listens to TCP connections, sends commands, and listens for events. I made the decision to utilize bluebird to eliminate callbacks, but I'm encountering an issue. I can't seem to catch a rejec ...

Steps for making a GET request from an API in Angular 7

Currently, I am attempting to retrieve JSON data using HttpClient in Angular 7. The code is functioning properly, but I am exploring the option of fetching the data directly from the API URL instead of relying on the const IMAGES array. import { Injectable ...

Steps for adding an HTML string to a div element using Ajax

I am facing some major challenges with Ajax, especially when it comes to appending HTML code to a div. I am attempting to append this HTML string to <div id="content-loader"></div> PHP function getLogo(){ $logo = '<div class="bg- ...

Retrieve a text file using FTP asynchronously and utilizing Promises in Node.js and AWS Lambda

Utilizing a single Node module called basic-ftp, I am tasked with downloading a txt file in AWS Lambda and storing it in the /tmp/ directory within the Lambda function. The goal is to manipulate the txt file and its contents outside of the FTP function. ...

Styling with CSS: Creating a scrollable gallery of images with a hover effect

I'm struggling to align multiple images horizontally on the page with a hover effect for each image. I can achieve one or the other separately, but not both together. As a beginner in HTML/CSS, I know it's a simple process. Below is my code with ...

The connection to the firebase callback

Upon examining this function, it appears that there may be an issue with a null value causing the error message to display: (node:16232) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'groupPages' of null async setTriggers() { ...

Issue with jQuery Master-Detail dropdown list selection

Having trouble isolating the code in this jsfiddle script. Despite my efforts, it seems that isolation is not working as expected and Firebug isn't showing any errors on the console: <!DOCTYPE html> <html lang="en"> <head> ...

Error encountered while submitting ajax request to server

When I click a button, a function is triggered with the argument insertSongPlay(newSong.songID);. After logging the value of newSong.songID, which is 90 as desired, an ajax call is made: function insertSongPlay(songID) { $.ajax ({ type: " ...

Reducing the number of DOM manipulations for websites that heavily utilize jquery.append

Here's a snippet of my coding style for the website: !function(){ window.ResultsGrid = Class.extend(function(){ this.constructor = function($container, options){ this.items = []; this.$container = $($container); ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

Enhancing react-confirm-alert: Steps to incorporate your personalized CSS for customizing default settings

I'm currently utilizing a confirmation popup feature provided by react-confirm-alert: popup = _id => { confirmAlert({ title: "Delete user", message: "Are you sure?", buttons: [ { label: ...

Unable to display response following the submission of a POST request

I'm encountering an issue when attempting to display the response of a post request using node and request. While I can see the response in the console within the service, it does not make its way to the controller. Any insights on why this may be hap ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Navigating through the maze of ES6 imports and dealing with the complexities

Currently, I am delving into React and creating my own components. However, the issue of project organization has arisen. Here is the structure of my project: Project_Folder - Components - Form - index.js - form.less - package.js ...

The information displayed in my Google snippet does not match the content of the intended URL

It may seem a bit confusing, so to clarify, here is an example: When you click the +1 button on this page, the snippet will display the text and URL from that specific page. However, in my case, the snippet displays text from the homepage URL instea ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...