【问题标题】:Using 'moment-weekday-calc' in node.js Typescript在 node.js Typescript 中使用“moment-weekday-calc”
【发布时间】:2020-11-16 22:47:30
【问题描述】:

无法在 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]
});   

可能的 Typescript 代码:

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.js typescript momentjs weekday


    【解决方案1】:

    为了使其正常工作,您可以使用 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 
    

    【讨论】:

      猜你喜欢
      • 2016-07-11
      • 2017-08-20
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2016-09-11
      相关资源
      最近更新 更多