0

I'm using TypeScript and a moment.js plugin called 'moment-transform'.

moment-transform dynamically adds a transform function to the moment object. Usage is something like this:

import moment = require('moment');
require('moment-transform'); // simply adds transform function

moment().transform('YYYY-MM-+07 00:00:00.000').toDate();

However, when building this with TypeScript, I get this error:

error TS2339: Property 'transform' does not exist on type 'Moment'.

How would I handle dynamically added functions properly?

[edit] (moment() as any).transform('YYYY-MM-+07 00:00:00.000').toDate(); seems to work. Is this really the way to go? Is there any possibility to specify this globally??

1 Answer 1

2

You can extend the moment definitions using the following approach:

Declare any extensions to moment in your custom 'moment.d.ts':

import * as moment from "moment";

declare module "moment" 
{
    interface Moment 
    {
        transform(a: string): Moment;
    }
}

And consume it in your 'my.ts':

import * as moment from 'moment';

moment().transform('qw').toDate();

More on the matter: Module Augmentation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.