7

In JavaScript, it is straight-forwardd to add functions and members to the prototype of any type. I'm trying to achieve the same in TypeScript as follows:

interface Date
{
    Minimum: Date;
}

Date.prototype.Minimum = function () { return (new Date()); }

This produces the following error:

Type '() => Date' is not assignable to type 'Date'.
Property 'toDateString' is missing in type '() => Date'.

Considering TS is strongly-types, how could we achieve this?

Since I'm writing a custom utility library in TS, I'd rather not resort to JS.

2 Answers 2

26

Interfaces don't get transpiled to JS, they're just there for defining types.

You could create a new interface that would inherit from the first:

interface IExtendedDate extends Date {
    Minimum: () => Date;
}

But for the actual implementations you will need to define a class. For example:

class ExtendedDate implements IExtendedDate {
    public Minimum(): Date {
        return (new ExtendedDate());
    }
}

However note that you can do all this without an interface.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted. In my view this is better than messing with the prototype of a buit-in object, even though JS let's you do it.
0

You can have it like this:

interface Date
{
    Minimum(): Date;
}

(<any>Date.prototype).Minimum = function () { return (new Date()); }

let d = new Date();
console.log(d.Minimum());

Hope this helps.

1 Comment

Note that the assertion to any is not necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.