ivayloc
ivayloc

Reputation: 375

Typescript typings for momentjs and moment-range not working together

I am using momentjs and moment-range with a Typescript, so I have install typings for moment-range from npm @types, and the typing for momentjs comes with it.

import * as moment from 'moment';
import 'moment-range';
...
private tableDatePeriod: moment.Range;

but on compile I am getting this error - [ts] Module 'moment' has no exported member 'Range'.

Upvotes: 0

Views: 1032

Answers (2)

JuanFran Adame
JuanFran Adame

Reputation: 39

The following works for me for versions:

  • moment: 2.17.1
  • moment-range: 2.2.0
  • @types/moment-range: 2.0.33

The problem is that moment-range.js does not export any new entity for the range functionality, it extends moment type with range functionalities. Therefore these functionalities should be imported from moment.

import {Moment, Range, range as RangeConstructor} from "moment";

This import loads the moment-range functionalities from moment. In this example I import Range interface and range factory method (to create/construct ranges). That should be enough, but in case you are using some type of AMD or similar dependency, the moment-range module should be loaded (required using AMD terms). The following is the hack that works for me:

import DateRange = require("moment-range");
DateRange;

The first import includes moment-rangemodule as a dependency of the current module, therefore it is loaded as required first. The second line does nothing, but the TypeScript compiler removes unused dependencies, so the former imported dependency must be invoked in some way in order to avoid such compiler optimization.

In reference to your question, you can now instantiate the variable:

private tableDatePeriod: Range;

And initialize:

tableDatePeriod = RangeConstructor('2016-01-09', '2016-01-10');

Upvotes: 0

Roman Ivanitskyi
Roman Ivanitskyi

Reputation: 21

Try this

import * as moment from 'moment';
import { default as DateRange } from 'moment-range';

let Range=new DateRange(dayFrom, dayTo);
Range.toArray('days');

let DatesArray=[];
diffDatesArray.push(moment(some_prop_from_array._d).format("YYYY-MM-DD"));

Upvotes: 1

Related Questions