2016-07-18 150 views
7

Ho provato a creare un metodo di estensione in TypeScript basato su questa discussione (https://github.com/Microsoft/TypeScript/issues/9), ma non sono riuscito a crearne uno funzionante.Come creare un metodo di estensione in TypeScript per il tipo di dati "Data"

Ecco il mio codice,

namespace Mynamespace { 
    interface Date { 
     ConvertToDateFromTS(msg: string): Date; 
    } 

    Date.ConvertToDateFromTS(msg: string): Date { 
     //conversion code here 
    } 

    export class MyClass {} 
} 

ma non il suo lavoro.

risposta

12

è necessario modificare il prototipo:

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

Anche se sembra che si desidera avere un metodo factory statica sull'oggetto Date, nel qual caso è meglio fare qualcosa di simile:

interface DateConstructor { 
    ConvertToDateFromTS(msg: string): Date; 
} 

Date.ConvertToDateFromTS = function(msg: string): Date { 
    // implement logic 
} 

let newDate = Date.ConvertToDateFromTS(TS_VALUE); 
+2

errore di lancio, 1. proprietà ConvertToDateFromTS non esiste sul tipo DateConstructor 2.property ConvertToDateFromTS non esiste sul tipo Data – AhammadaliPK

+0

Dove vengono visualizzati questi errori? Funziona per me: [code in playground] (https://www.typescriptlang.org/play/#src=interface%20DateConstructor%20%7B%0D%0A%20%20%20%20ConvertToDateFromTS (msg% 3A% 20string)% 3A% 20Date% 3B% 0D% 0A% 7D% 0D% 0A% 0D% 0ADate.ConvertToDateFromTS% 20% 3D% 20function (msg% 3A% 20string)% 3A% 20Date% 20% 7B% 0D% 0A% 09return% 20null% 3B% 0D% 0A% 7D% 0D% 0A% 0D% 0Ainterface% 20Date% 20% 7B% 0D% 0A% 20% 20% 20% 20ConvertToDateFromTS (msg% 3A% 20string)% 3A% 20Date% 3B % 0D% 0A% 7D% 0D% 0A% 0D% 0ADate.prototype.ConvertToDateFromTS% 20% 3D% 20function (msg% 3A% 20string)% 3A% 20Date% 20% 7B% 0D% 0A% 20% 20% 20% 20return% 20null% 3B% 0D% 0A% 7D) –

+1

Non hai aggiunto nulla alla tua domanda che risponda a ciò che ti ho chiesto. Ti ho dato una risposta su come fare ciò che vuoi, hai detto che ci sono errori e ho chiesto dove li prendi? e anche fornito un collegamento allo stesso codice in un campo da gioco che mostra chiaramente che il codice viene compilato senza errori. –