Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have tried to create an extension method in TypeScript based on this discussion (https://github.com/Microsoft/TypeScript/issues/9), but I couldn't 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 its not working.

like image 333
AhammadaliPK Avatar asked Jul 18 '16 10:07

AhammadaliPK


People also ask

How do I extend a class in TypeScript?

Just like object-oriented languages such as Java and C#, TypeScript classes can be extended to create new classes with inheritance, using the keyword extends . In the above example, the Employee class extends the Person class using extends keyword.

Can we create extension method for interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

Where do you write extension methods?

Select File > New > Project and select Visual C# and Console Application as shown below. Add the reference of the previously created class library to this project. In the above code, you see there is a static class XX with a method, NewMethod.


1 Answers

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); 

Though it looks like you want to have a static factory method on 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); 
like image 117
Nitzan Tomer Avatar answered Sep 26 '22 08:09

Nitzan Tomer