Extending momentjs functionality with a custom method in Typescript

I am attempting to extend the momentjs prototype with a new function. In JavaScript, I achieved this with the following code:

Object.getPrototypeOf(moment()).isWeekend = function() {
    return this.isoWeekday() >= 6;
};

How can I accomplish this in TypeScript? I have been advised to duplicate the interface and add my function to it, but my attempt so far has not been successful:

module moment {
    interface Moment {
        isWeekend(): boolean
    }

    Moment.prototype.isWeekend = () => {
        this.isoWeekday() >= 6;
    };
}

Answer №1

In order to properly set up the extension, make sure to place it outside of the module and export the interface...

module time {
    export interface TimeExtension {
        isWeekend(): boolean
    }
}

(<any>time).fn.isWeekend = function() {
    this.dayOfWeek() >= 6;
};

Answer №2

It's actually working perfectly for me.

import * as moment from 'moment';
declare module 'moment' {
  export interface Moment {
    toJapaneseEra(): number;
  }
}

(moment.fn as any).toJapaneseEra = function () {
  const _self = this as moment.Moment;
  return _self.year() - 1988;
}

For more details, please check out:

https://medium.com/my-life/extension-method-in-typescript-66d801488589

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

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Importing images in Typescript is a simple and effective

I came across a helpful solution at this Stackoverflow thread However, I encountered an error: [ts] Types of property 'src' are incompatible. Type 'typeof import("*.png")' is not assignable to type 'string | undefined& ...

A solution to the error message "Type 'unknown' is not assignable to type 'Country[]' in React TypeScript" is to explicitly define the type of the

I encountered error TS2322: Type 'unknown' is not assignable to type 'Country[]' pages/Countries/index.tsx Full code: import * as ApiCountries from '../../services/APIs/countries.api' function Countries() { const findCo ...

Is there an issue with this return statement?

retrieve token state$.select(state => { retrieve user access_token !== ''}); This error message is what I encountered, [tslint] No Semicolon Present (semicolon) ...

Is the detection change triggered when default TS/JS Data types methods are called within an HTML template?

I'm currently updating an application where developers originally included function calls directly in the HTML templating, like this: <span>{{'getX()'}}</span> This resulted in the getX method being called after each change dete ...

What is the most efficient way to apply multiple combinations for filtering the information within a table?

I'm facing an issue with my Angular project. I have 4 select boxes that allow users to apply different filters: office worker project name employee activities The problem I'm encountering is the difficulty in predicting all possible combination ...

Is using global variables as a namespace a good practice? Creating ambient TypeScript definitions in StarUML

I'm currently working on creating TypeScript type definitions for the StarUML tool. While I've been successful in defining most of the API, I've hit a roadblock when it comes to linking a JavaScript global variable ("type" in this case) with ...

What is the best way to bring in the angular/http module?

Currently, I am creating an application in Visual Studio with the help of gulp and node. Node organizes all dependencies into a folder named node_modules. During the build process, gulp transfers these dependencies to a directory called libs within wwwroo ...

Issues arise when trying to implement Angular class and it does

I'm currently facing some challenges using classes in Angular to simplify my coding process. So far, I haven't been able to get it to work properly. Below is the code snippet I'm working with and the error message that pops up: import { Wiz ...

Why do referees attempt to access fields directly instead of using getters and setters?

I am facing an issue with my TypeScript class implementation: class FooClass { private _Id:number=0 ; private _PrCode: number =0; public get Id(): number { return this._Id; } public set Id(id: number) { this._Idprod ...

Can a single data type be utilized in a function that has multiple parameters?

Suppose I have the following functions: add(x : number, y : number) subtract(x : number, y : number) Is there a way to simplify it like this? type common = x : number, y : number add<common>() This would prevent me from having to repeatedly define ...

Tips for injecting a service into a class (not a component)

Can you inject a service into a class that is not a component? Consider the following scenario: Myservice import {Injectable} from '@angular/core'; @Injectable() export class myService { dosomething() { // implementation } } MyClass im ...

ts-jest should replace the character '@' with the '/src' folder in the map configuration

I have set up a node project using TypeScript and configured various paths in my tsconfig.json file, such as: "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl' ...

Issue with ngx-bootstrap custom typeahead feature malfunctioning

I'm facing an issue while trying to develop a customized typeahead feature that is supposed to search my API every time the user inputs something, but it's not functioning as expected. The autocomplete() function isn't even getting accessed. ...

typeorm migration:generate - Oops! Could not access the file

When attempting to create a Type ORM migration file using the typeorm migration:generate InitialSetup -d ormconfig.ts command, I encountered an error: Error: Unable to open file: "C:\_work\template-db\ormconfig.ts". Cannot use impo ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state. My goal is to specifically fetch the 'numberOf ...

Utilizing Directives to Embed Attributes

My current challenge involves changing the fill color of attributes in an in-line SVG using Angular and TypeScript. The goal is to have the SVG elements with a "TA" attribute change their fill color based on a user-selected color from a dropdown menu. Howe ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...

Theme not being rendered properly following the generation of a dynamic component in Angular

I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file a ...