将Moment代码转Luxon获预期输出但VSCode报类型不匹配错误
Moment转Luxon后类型不匹配问题解决
问题场景
将Moment日期处理代码转换为Luxon实现后,运行输出与预期一致,但在VSCode中hoverdate[0]时出现类型不匹配错误。
原Moment代码
const date8 = ''; console.log(`This moment date Method 8 : `, moment(date8[0]).startOf('hour'));
输出结果:
This moment date Method 8 : 2022-12-02T14:00:00.000Z
转换后的Luxon代码
const date9 = ''; console.log( `This luxon date Method 8 : `, luxon.DateTime.utc(date9[0]).startOf('hour') );
输出结果:
This luxon date Method 8 : 2022-12-02T14:00:00.000Z
VSCode错误信息
No overload matches this call. Overload 1 of 8, '(year: number, options?: LocaleOptions | undefined): DateTime', gave the following error. Argument of type 'Date' is not assignable to parameter of type 'number'. Overload 2 of 8, '(options?: LocaleOptions | undefined): DateTime', gave the following error. Type 'Date' has no properties in common with type 'LocaleOptions'.
问题原因
Moment构造函数容错性极强,传入undefined(空字符串''的[0]索引值为undefined)时会返回当前UTC时间;但Luxon的DateTime.utc()方法没有接收undefined的重载,VSCode的JS/TS语言服务会检测到类型不匹配,抛出错误。
解决方法
直接调用无参的luxon.DateTime.utc(),即可得到与原Moment代码一致的当前UTC时间,同时解决类型错误:
const date9 = ''; console.log( `This luxon date Method 8 : `, luxon.DateTime.utc().startOf('hour') );
如果需要兼容可能存在有效日期字符串的场景,可以添加条件判断:
const date9 = ''; const targetDate = date9[0] ? luxon.DateTime.fromISO(date9[0]) : luxon.DateTime.utc(); console.log(`This luxon date Method 8 : `, targetDate.startOf('hour'));
内容的提问来源于stack exchange,提问作者GCT
相关产品推荐
相关产品推荐

