Creating a new function within the moment.js namespace in Typescript

I am attempting to enhance the functionality of the moment.js library by adding a new function that requires a moment() call within its body. Unfortunately, I am struggling to achieve this.

Using the latest version of Typescript and moment.js, I have searched for a solution without success. Although I found a potential solution (Typescript: add function to momentjs' prototype) that seemed promising, it hasn't worked for me.

My current code snippet is as follows:

import * as moment from 'moment';

export namespace moment{
    interface Moment{
        myFunc(): boolean;
    }
}

(moment as any).fn.myFunc = function() {
    return moment(....);
};

I am not certain where the issue lies, as when attempting to use the moment library along with myFunc, importing moment (import * as moment from 'moment') does not seem to be enough – myFunc is not recognized, only the standard moment functions.

For example, when using myFunc(), it gives an error indicating that myFunc() is not recognized:

import * as moment from 'moment'
import Moment = moment.Moment

... moment().add(...) //works
... moment().myFunc() // doesn't recognize myFunc()

Any recommendations on how to resolve this issue and make it work?

Answer №1

To incorporate your custom myFunc into the moment library using TypeScript, you can utilize declaration merging.

Below is an approach that worked for me with TypeScript version 2.4.2:

import * as moment from 'moment';

declare module "moment" {
  interface Moment {
    myFunc(): moment.Moment;
  }
}

(moment as any).fn.myFunc = function (): moment.Moment {
  console.log("Invoked myFunc!");
  return moment();
};

console.log(moment().myFunc().valueOf());

The above code snippet produces the following output:

Invoked myFunc!
1501901308611

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

Display highlighted option in material dropdown

Is there a way to display the selected value on the label in this code? Thanks for any help! ...

The Express application remains silent unless a port is specified for it to

Having recently started working with Node, I encountered an issue with Express. My application is only listening to localhost:PORT and I want it to also listen to just localhost. Here is the code snippet: ** var app = require('../app'); var debu ...

Animating Page Transitions using Angular 2.0 Router

Seeking to implement animated transitions for new components using the onActivate method in Angular 2. A Plunk has been set up to demonstrate the issue at hand: http://plnkr.co/FikHIEPONMYhr6COD9Ou Here is an example of the onActivate method within a pag ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Sending information to a single component among several

I'm developing a custom DownloadButton component in VueJS that features an animation when clicked and stops animating once the download is complete. The DownloadButton will be utilized within a table where it's replicated multiple times. I intend ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...

What possible reasons could cause the installation of Visual Studio 2017 to disrupt node.js or the typescript compiler?

Recently, I updated to the latest version of Visual Studio 2017 and selected the node.js support option during installation. However, after this update, I encountered issues with the typescript compiler (tsc) in an Angular 2 project that was last modified ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...

Postman successfully validates the API, however, it experiences issues when run in Mocha JS

When testing my API with Postman, everything works fine. However, when I try to test the same API with Mocha JS using the same data, I am encountering errors such as "500 internal server error" and "400 bad request". I have double-checked that I am passin ...

The Next JS build process exclusively creates server-side pages

I have noticed that some of my pages like /contact, /about, and /rules are server-side generated even though I am not using getServerSideProps(). Since these pages only contain static images and text without any API requests, I want them to be treated as s ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

fixing errors with express, angularJS, and socket.io

I am currently in the process of setting up Socket.io on my website using ExpressJS and AngularJS NodeJS server.js var express = require('express'); var app = express(); fs = require('fs'); // specifying the port ...

What is the best way to implement this ajax preloader?

<script type="text/javascript"> $(document).ready(function() { $('#loading') .hide() .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); } ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...

What is the best way to retrieve the value of this object?

In my project, I am utilizing Angular 8 to extract data from a radio input. However, when I transmit this data to Node.js and then to a MongoDB database, it is not being properly registered. The entry in the database collection appears as follows: "__v" : ...

Implementing real-time time updates using php ajax technology

It's fascinating how websites can update the time dynamically without using ajax requests. I currently have a comment system in place. $('#comment').click(function(){ $.post(url,{ comment : $(this).siblings('textarea.#commen ...

What is the best way to access the EXIF data of an image (JPG, JPEG, PNG) using node.js?

In my quest to access the EXIF data of an image in order to extract GPS information such as Latitude and Longitude, I have experimented with approximately 4-5 EXIF packages available on npm/node, including exif, exif-parser, node-exif, exifr, exif-js, and ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data ...