如何在TypeScript中为“日期"数据类型创建扩展方法 [英] How to create an extension method in TypeScript for 'Date' data type

查看:567
本文介绍了如何在TypeScript中为“日期"数据类型创建扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此讨论,我试图在TypeScript中创建扩展方法( https: //github.com/Microsoft/TypeScript/issues/9 ),但我无法创建一个有效的文件.

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.

这是我的代码,

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

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

    export class MyClass {}
}

但无法正常工作.

推荐答案

您需要更改原型:

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

尽管您似乎希望对Date对象使用静态工厂方法,但在这种情况下,您最好执行以下操作:

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

这篇关于如何在TypeScript中为“日期"数据类型创建扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆