orad
orad

Reputation: 16084

Extending Date.prototype in TypeScript

Please help me understand why this works for Number but not for Date.

declare interface Number {
    toPreferredStringFormat(): string;
}

declare interface Date {
    toPreferredStringFormat: string;
}

(function () {
    // OK
    Number.prototype.toPreferredStringFormat = () => {
        return this.toString() + " preferred!";
    };

    // ERROR (why?!)
    Date.prototype.toPreferredStringFormat = () => {
        return this.toString() + " preferred!";
    };
})();

Am I doing it right?

Thanks!

Upvotes: 4

Views: 12288

Answers (2)

Miloš Stanić
Miloš Stanić

Reputation: 520

What worked for me, when I wanted to extend Date prototype with a new method is this:

declare global {
    interface Date{
        yyyymmdd: () => string;    
    }
}

I picked this up from here

Upvotes: 12

Fenton
Fenton

Reputation: 251102

There is a subtle difference between your two declarations...

toPreferredStringFormat(): string; // has ()
toPreferredStringFormat: string; // doesn't have ()

The second of these two says the property is a string, the first says it is a function.

Here is a full working example, using the long-hand way of saying that you expect a function returning a string, this makes it more obvious than just the presence of brackets, but that works too:

declare interface Number {
    toPreferredStringFormat: () => string;
}

declare interface Date {
    toPreferredStringFormat: () => string;
}

(function () {
    // OK
    Number.prototype.toPreferredStringFormat = () => {
        return this.toString() + " preferred!";
    };

    // ERROR (why?!)
    Date.prototype.toPreferredStringFormat = () => {
        return this.toString() + " preferred!";
    };
})();

Upvotes: 7

Related Questions