rotaready / moment-range

Fancy date ranges for Moment.js
The Unlicense
1.69k stars 202 forks source link

Can't create open-ended ranges in TypeScript #264

Open sarbogast opened 5 years ago

sarbogast commented 5 years ago

I'm trying to create open-ended ranges in a TypeScript class, but moment.range() seems to only accept Dates or Moments as inputs, not null or undefined.

import * as Moment from 'moment'
import { extendMoment, MomentRange, DateRange } from 'moment-range'
import {isNullOrUndefined} from "util";

const moment = extendMoment(Moment) as unknown as typeof Moment & MomentRange;

export class Time {
    constructor(
        public startDate: Moment.Moment | undefined,
        public endDate: Moment.Moment | undefined
    ) {}

    overlapsWith(otherTime: Time): DateRange | undefined {
        if((this.startDate === undefined && this.endDate === undefined)
            || (otherTime.startDate === undefined && otherTime.endDate === undefined)) {
            return undefined;
        }

        const thisRange = moment.range(this.startDate, this.endDate);
        const otherRange = moment.range(otherTime.startDate, otherTime.endDate);
        const intersection = thisRange.intersect(otherRange);
        if(intersection === null) {
            return undefined;
        } else {
            return intersection;
        }
    }
}

Those 2 lines fail:

const thisRange = moment.range(this.startDate, this.endDate);
const otherRange = moment.range(otherTime.startDate, otherTime.endDate);
beaumontjonathan commented 5 years ago

Hi @sarbogast, thanks for raising this issue! It does appear to be a bug. I'll get on this shortly 😀

bilottafra commented 2 years ago

I still experience the same problem, but I managed to solve it. Instead of: const openRange = moment.range(start, null) I used: const openRange = moment.range(start, moment())

In my case logically it had the same effect.

InesCayollaV commented 1 year ago

When creating open-ended ranges, the problem still persists, it appears that pull-request #273 was intended to solve it, but it was eventually reverted. Regarding @francescobilotta's answer, using const openRange = moment.range(start, moment())would create a range from the provided start date up to the current date, rather than an open range. I managed to create an open range with const openRange = moment.range(start) although I had to ignore the TypeScript error.