6

I'm trying to calculate start date and end date of a week from the given date range.

Below code gives me this error [ts] Property 'getWeek' does not exist on type 'Date'.

  Date.prototype.getWeek = function(start)
{
    start = start || 0;
    var today = new Date(this.setHours(0, 0, 0, 0));
    var day = today.getDay() - start;
    var date = today.getDate() - day;

    var StartDate = new Date(today.setDate(date));
    var EndDate = new Date(today.setDate(date + 6));
    return [StartDate, EndDate];
}

var Dates = new Date().getWeek();
colxi
  • 7,640
  • 2
  • 45
  • 43
arunkumar
  • 333
  • 1
  • 9
  • 25

3 Answers3

11

You need to declare the method on the Date interface using interface merging

declare global {
    interface Date {
        getWeek (start?: number) : [Date, Date]
    }
}
Date.prototype.getWeek = function(start)
{
    start = start || 0;
    var today = new Date(this.setHours(0, 0, 0, 0));
    var day = today.getDay() - start;
    var date = today.getDate() - day;

    var StartDate = new Date(today.setDate(date));
    var EndDate = new Date(today.setDate(date + 6));
    return [StartDate, EndDate];
}

var Dates = new Date().getWeek();

Or if you are not using modules:

interface Date {
    getWeek (start?: number) : [Date, Date]
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • If this helps anyone, I had to add `export { };` at the top of my file to allow this to work. I'm no TS expert by any stretch, so cannot comment on why that was needed. – dotNET May 25 '23 at 10:24
2

Date is declared as a known interface by TypeScript. getWeek is not a property of Date a so it won't let you get or modify it.

You must augment the Date interface:

Add a new global.d.ts file. In it:

interface Date {
    getWeek: (start: number | undefined) => [Date, Date];
}

Then, TypeScript will mix both declarations, and so it will recognise the existence of getWeek and you can define it in your code (another file, as declaration files can't contain statements)

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0

This is because of how typescript handles extensions. You can fix your issue by modifying the interface of Date like this:

interface Date {
    getWeek(start): Array<Date>;
}

  Date.prototype.getWeek = function(start)
{
    start = start || 0;
    var today = new Date(this.setHours(0, 0, 0, 0));
    var day = today.getDay() - start;
    var date = today.getDate() - day;

    var StartDate = new Date(today.setDate(date));
    var EndDate = new Date(today.setDate(date + 6));
    return [StartDate, EndDate];
}

var Dates = new Date().getWeek();
bugs
  • 14,631
  • 5
  • 48
  • 52