使用接口 Typescript 扩展日期原型 [英] Extend Date prototype with a interface Typescript

查看:53
本文介绍了使用接口 Typescript 扩展日期原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 javascript/typescript 中向 Date 原型添加一个 getWeekNumber 函数.我想用一个接口来做,因为否则我会得到一个错误,他不知道 getWeekNumber() 方法.

I want to add a getWeekNumber function to the Date prototype in javascript / typescript. I want to do it with an interface becease otherwise I get a error that he does not know the method getWeekNumber().

首先我尝试使用这样的标准日期界面:

First I tried with a standart Date interface like this:

interface Date {
    getWeekNumber(): number;
}

这解决了 Date 的所有方法都无法再调用的问题.

This had the resolve that all the methods of the Date are not call able anymore.

我想知道有一种方法可以使用接口扩展日期.

I want to know of there is a way to extend the Date with an interface.

推荐答案

你可以这样做:

在 DateExt.ts 中:

in DateExt.ts:

interface Date 
{
    getWeekNumber: () => number;
}

Date.prototype.getWeekNumber = function() 
{
    return 123;//your calculations goes here
};

在您的 app.ts 中:

in your app.ts:

import './DateExt';

let a = new Date();
console.log(a.getWeekNumber());

这篇关于使用接口 Typescript 扩展日期原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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