如何在TypeScript中使用moment-duration格式?

时间:2017-03-28 00:48:42

标签: javascript angular typescript momentjs

我在我的TypeScript(Ionic2 / Angular2)项目中使用了moment.js。继this post之后,我现在想尝试一个插件moment-duration-format

我有npm包和类型定义,并且可以通过import使用..

import moment from 'moment';
...
let duration = moment.duration(decimalHours, 'hours');

我现在想要使用moment-duration-format

我已通过npm install moment-duration-format --save安装,然后通过npm i @types/moment-duration-format --save安装了类型定义。

我可以看到两个npm模块。

与往常一样,关于如何使用这种类型定义总是存在一些谜团(包括导入的用法似乎永远不会出现在任何doco中)。

我尝试添加import 'moment-duration-format';import duration from 'moment-duration-format';(moment-duration-format / index.d.ts'不是模块。)

尝试使用时出现错误,如下所示..

let dd = moment.duration.format(400.99, 'hours').format('D:HH:mm');

// (TS error [ts] Property 'format' does not exist on type '(inp?: DurationInputArg1, unit?: DurationConstructor) => Duration'.

有没有人知道如何在 TypeScript 中使用它。

提前致谢

4 个答案:

答案 0 :(得分:6)

我正在使用解决方法here,但现在看起来已经修复了ype def。获取def类型的更新所以我可以执行以下操作...

import * as moment from 'moment';
import 'moment-duration-format';

let duration = moment.duration(decimalHours, 'hours') ;   
let options : moment.DurationFormatSettings   = {
  forceLength : false,
  precision : 0,
  template : formatString,
  trim : false
};
let result  = duration.format(formatString, 0, options);

答案 1 :(得分:1)

您使用duration作为属性而不是调用它。尝试:

let dd = moment.duration(400.99, 'hours').format('D:HH:mm');

这实际上不是TypeScript问题。它也无法使用JavaScript。在JavaSctript中,您会遇到运行时错误,而TypeScript不允许您在编译时执行此操作(证明其价值)。

答案 2 :(得分:1)

我遇到了同样的问题...

似乎类型定义中存在错误。其他人有同样的问题,你可以在这里看到:https://github.com/souldreamer/noti-cli/blob/ef104c22792e0dfeb67d3372b04e231d45ffaa55/src/shared/pipes.ts#L38

作为github上的pull请求的一部分,有一个问题的修复程序,遗憾的是,它已经关闭而没有合并: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/14327

作为临时解决方法,您可以使用第一个链接的代码行。作为第二步,我们应该尝试在github上创建一个新的pull请求,以便在将来的版本中修复问题。

答案 3 :(得分:0)

问题是当R_B_在typings模块中正确计算出一个错误的类型定义,用于moment-duration-format。

我会为此创建一个新的拉取请求,因为我的上一次因lint错误而被关闭。

您可以在项目中使用自定义类型定义 https://github.com/TwoStone/leaderboard/blob/develop/subprojects/webapp/src/custom-typings.d.ts 只需在项目中创建文件,它应该可以正常工作。