qqilihq
qqilihq

Reputation: 11474

TypeScript and moment-transform with dynamically added function

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??

Upvotes: 0

Views: 280

Answers (1)

Amid
Amid

Reputation: 22372

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

Upvotes: 2

Related Questions