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

倾然丶 夕夏残阳落幕 提交于 2019-11-29 07:12:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/38434337/how-to-create-an-extension-method-in-typescript-for-date-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!