Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending an interface in TypeScript

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.

like image 248
Raheel Khan Avatar asked Mar 19 '16 09:03

Raheel Khan


1 Answers

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.

like image 139
obe Avatar answered Sep 22 '22 21:09

obe