moment-range
moment-range copied to clipboard
TypeError: moment is not a function
There is an issue with typescript usage.
- "typescript": "^4.9.5"
- "jest": "^29.1.2",
- "ts-jest": "^29.0.5"
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"useUnknownInCatchVariables": false,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"@/*": [
"./*"
]
},
"types": [
"jest",
"@types/node",
"@nuxt/types",
"@nuxtjs/axios",
"@nuxtjs/vuetify",
"@nuxt/vue-app",
"@nuxtjs/i18n",
"vue-i18n/types"
]
},
"exclude": [
"node_modules",
".nuxt",
"dist"
]
}
some.test.ts
import * as m from 'moment';
import { DateRange, extendMoment } from 'moment-range';
const moment = extendMoment(m);
const availableSince1 = moment('2023-04-06T08:00:00.000Z');
// ^ TypeError: moment is not a function
I was trying this approach but another error occurred
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
Array.from(
moment
.range('2023-04-06T08:00:00.000Z', '2023-04-06T13:30:00.000Z')
.by('minutes', { step: stepInMinutes })
).map((time) => ({ date: time.toLocaleString() })); // 'time' is of type 'unknown'.
// then I tried to cast to the type
Array.from(
moment
.range('2023-04-06T08:00:00.000Z', '2023-04-06T13:30:00.000Z')
.by('minutes', { step: stepInMinutes })
).map((time) => ({ date: time.toLocaleString() })); // 'time' is of type 'unknown'.
/*
Argument of type '(time: m.Moment) => { date: string; }' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => { date: string; }'.
Types of parameters 'time' and 'value' are incompatible.
Type 'unknown' is not assignable to type 'Moment'.
*/
I have the same issue, it's not compatible with TypeScript environment.
The following works for me.
import Moment from "moment";
import { extendMoment } from "moment-range";
// @ts-expect-error - No proper typescript support from moment-range
const moment = extendMoment(Moment);
Array.from(
moment
.range(moment('2023-04-06T08:00:00.000Z'), moment('2023-04-06T13:30:00.000Z'))
.by('minutes', { step: stepInMinutes })
).map((time) => ({ date: time.toLocaleString() }));