moment().add()仅适用于文字值

roc*_*ter 18 momentjs typescript angular

我在TypeScript中使用Moment.js(如果重要的话,在Angular 2下).当我使用带有文字值的add()方法作为参数时,它工作正常:

moment().add(1, 'month');
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试用字符串替换单位,它将失败:

let units:string = 'month';
moment().add(1, units);
Run Code Online (Sandbox Code Playgroud)

有这个错误:

Argument of type '1' is not assignable to parameter of type 'DurationConstructor'.
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Ale*_* L. 24

不推荐的反向过载add(unit: unitOfTime.DurationConstructor, amount: number|string)会产生歧义.

您可以通过定义类型的解决这个问题的unitsDurationConstructor不是string:

let units: moment.unitOfTime.DurationConstructor = 'month';
moment().add(1, units);
Run Code Online (Sandbox Code Playgroud)

  • `DurationConstructor`是一个字符串文字类型的联合(比如`type Foo ='month'|'week'| ...`),它可以防止你将无效/不支持的字符串作为单位参数传递.所以你最好将函数签名更改为`addOneUnit(date:Date,units:moment.unitOfTime.DurationConstructor)`.另一种选择是使用类型断言(`units as moment.unitOfTime.DurationConstructor`) - 但是你将失去类型安全性. (2认同)

小智 8

接受答案的另一个选择是在参数中进行类型转换。真的没有区别,只是想我会把这个答案作为一个选项。如果您想要更简洁,也可以从 moment 导入 unitOfTime 作为模块。

import { unitOfTime } from 'moment';
import * as moment from 'moment';

option = {val: 30, unit: 'm'}
moment().add( this.querySince.val, <unitOfTime.DurationConstructor>this.querySince.unit )
Run Code Online (Sandbox Code Playgroud)


Amm*_*eel 5

不幸的是,上述答案都不适用于我!但这只是制造了魅力!:D

const startTime = moment().subtract(this.time.amount as moment.DurationInputArg1, this.time.unit as moment.DurationInputArg2);
Run Code Online (Sandbox Code Playgroud)