How to create an extension method in TypeScript for a Date data type

I tried to create an extension method in TypeScript based on this discussion ( https://github.com/Microsoft/TypeScript/issues/9 ), but I could not create a working one.

Here is my code

namespace Mynamespace { interface Date { ConvertToDateFromTS(msg: string): Date; } Date.ConvertToDateFromTS(msg: string): Date { //conversion code here } export class MyClass {} } 

but does not work.

+7
extension-methods typescript
source share
1 answer

You need to change the prototype:

 interface Date { ConvertToDateFromTS(msg: string): Date; } Date.prototype.ConvertToDateFromTS = function(msg: string): Date { // implement logic } let oldDate = new Date(); let newDate = oldDate.ConvertToDateFromTS(TS_VALUE); 

Although it looks like you want to use the static factory method for the Date object, in which case you better do something like:

 interface DateConstructor { ConvertToDateFromTS(msg: string): Date; } Date.ConvertToDateFromTS = function(msg: string): Date { // implement logic } let newDate = Date.ConvertToDateFromTS(TS_VALUE); 
+12
source share

All Articles