Aha*_*iPK 17 extension-methods typescript
我试图基于这个讨论(https://github.com/Microsoft/TypeScript/issues/9)在TypeScript中创建一个扩展方法,但我无法创建一个工作的方法.
这是我的代码,
namespace Mynamespace {
interface Date {
ConvertToDateFromTS(msg: string): Date;
}
Date.ConvertToDateFromTS(msg: string): Date {
//conversion code here
}
export class MyClass {}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
Nit*_*mer 26
你需要改变原型:
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);
Run Code Online (Sandbox Code Playgroud)
虽然看起来你想在Date对象上有一个静态工厂方法,但在这种情况下你最好做一些像:
interface DateConstructor {
ConvertToDateFromTS(msg: string): Date;
}
Date.ConvertToDateFromTS = function(msg: string): Date {
// implement logic
}
let newDate = Date.ConvertToDateFromTS(TS_VALUE);
Run Code Online (Sandbox Code Playgroud)
Kor*_*yem 14
之前的答案给出了 Typescript 错误
发现这个效果很好!
export {}
declare global {
interface Date {
addDays(days: number): Date;
}
}
Date.prototype.addDays = function (days: number): Date {
if (!days) return this;
let date = this;
date.setDate(date.getDate() + days);
return date;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25432 次 |
| 最近记录: |