首页 > 解决方案 > 在 node.js Typescript 中使用“moment-weekday-calc”

问题描述

无法在 Node.Js Typescript 项目中使用 Javascript 插件“moment-weekday-calc”。
moment-weekday-calc 没有打字版本。

我用 Javascript 编写的代码:

const moment = require('moment');
require('moment-weekday-calc');

const result = moment().dateRangeToDates({
      rangeStart,
      rangeEnd,
      exclusions,
      weekdays: [1, 2, 3, 4, 5]
});   

潜在的打字稿代码:

import * as moment from 'moment';
import 'moment-weekday-calc';

const result = moment().dateRangeToDates({
      rangeStart,
      rangeEnd,
      exclusions,
      weekdays: [1, 2, 3, 4, 5],
})

错误:“Moment”类型上不存在属性“dateRangeToDates”.ts(2339)

我尝试过类似declare module 'moment-weekday-calc'但仍然没有运气的方法,我认为 moment-weekday-calc 无法将新模块添加到 moment.

感谢你在期待。

标签: node.jstypescriptmomentjsweekday

解决方案


为了使其正常工作,您可以使用 TypeScript 的声明合并扩展 moment 以包含“moment-weekday-calc”函数。但是您必须自己定义每个功能。然后只需在要使用这些功能的地方使用 require('moment-weekday-calc') 。

要使用“moment-weekday-calc”中的 isoWeekdayCalc/weekdayCalc:

import moment from 'moment';

declare module "moment" {
    interface Moment {
        isoWeekdayCalc(d1: Date | string, d2: Date | string, weekDays: number[], exclusions?: string[], inclusion?: string[]): number
        weekdayCalc(d1: Date | string, d2: Date | string, weekDays: string[] | number[], exclusions?: string[], inclusion?: string[]): number
    }
}

另一种解决方法,只需在调用函数之前添加 //@ts-ignore

//@ts-ignore
moment().weekdayCalc('1 Apr 2015','31 Mar 2016',[1,2,3,4,5],['6 Apr 2015','7 Apr 2015'],['10 Apr 2015']); //260 

推荐阅读