node.js - 在 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.
感谢你在期待。
解决方案
为了使其正常工作,您可以使用 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
推荐阅读
- excel - 使用 Python 用多个 excel 文件中的列表中的信息填充新列
- c# - 在 .Net Core 3.1 类库中调用 iText7 PdfAcroForm.GetAcroForm() 时出现空引用异常
- spring-boot - 从 Spring Cloud Config 中的 application.properties 加载属性,直到刷新
- c++ - 任意大小的数据/向量/数组的原子和无锁写入
- c++ - 嵌套类中的 std::stack 数据成员导致内存泄漏
- asp.net-mvc - 使用多个表单时验证失败
- acumatica - 账单和调整屏幕 AP301000 在明细部分显示库存 ID,但在 BillDetail 类中没有 InventoryID 属性
- python - 如何使用 API 密钥作为密钥生成 HMAC-SHA256 签名
- reactjs - 如何将 RectIntl 格式化消息添加为 html 属性
- scala - Spark读取数据集错误且奇怪