[英]Extend Date prototype with a interface Typescript
I want to add a getWeekNumber function to the Date prototype in javascript / typescript. 我想在javascript / typescript中的Date原型中添加一个getWeekNumber函数。 I want to do it with an interface becease otherwise I get a error that he does not know the method getWeekNumber(). 我想用接口来做,因为否则我得到一个错误,他不知道方法getWeekNumber()。
First I tried with a standart Date interface like this: 首先,我尝试使用如下标准的Date接口:
interface Date {
getWeekNumber(): number;
}
This had the resolve that all the methods of the Date are not call able anymore. 这样就解决了Date的所有方法都不再能够调用的问题。
I want to know of there is a way to extend the Date with an interface. 我想知道有一种方法可以通过接口扩展Date。
You can do it this way: 您可以这样操作:
in DateExt.ts: 在DateExt.ts中:
interface Date
{
getWeekNumber: () => number;
}
Date.prototype.getWeekNumber = function()
{
return 123;//your calculations goes here
};
in your app.ts: 在您的app.ts中:
import './DateExt';
let a = new Date();
console.log(a.getWeekNumber());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.