如何在 TypeScript 中为“Date”数据类型创建扩展方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38434337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:13:45  来源:igfitidea点击:

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

typescriptextension-methods

提问by AhammadaliPK

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.

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

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.

但它不工作。

回答by Nitzan Tomer

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 Dateobject, in which case you better do something like:

虽然看起来您希望在Date对象上有一个静态工厂方法,但在这种情况下,您最好执行以下操作:

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

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

let newDate = Date.ConvertToDateFromTS(TS_VALUE);