Extending an interface in TypeScript
Solution 1
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.
Solution 2
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.
![Raheel Khan](https://i.stack.imgur.com/iEBVp.jpg?s=256&g=1)
Raheel Khan
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian Kernighan
Updated on July 19, 2022Comments
-
Raheel Khan almost 2 years
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.
-
David Sherret over 8 yearsNote that the assertion to
any
is not necessary. -
Aaron Beall over 8 yearsUpvoted. In my view this is better than messing with the prototype of a buit-in object, even though JS let's you do it.