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

后端 未结 1 1221
别那么骄傲
别那么骄傲 2020-12-14 16:49

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 worki

相关标签:
1条回答
  • 2020-12-14 16:57

    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);
    
    0 讨论(0)
提交回复
热议问题