LoginSignup
1
0

More than 3 years have passed since last update.

TypeScript2.3.2でmoment-duration-formatを使う

Last updated at Posted at 2019-11-26

注意

moment-duration-formatでは、バージョン2でTypeScript対応がアナウンスされているようです。より新しいバージョンのmoment-duration-formatを使用している場合、アップデートで対応できる可能性がありますのでGitHubを確認してください。
https://github.com/jsmreese/moment-duration-format

環境

Vue.jsを使ったJavaScript(ES6)のコードをWebPackで固めてクライアントサイドで実行している。
エディタはVSCode

背景

前の記事 https://qiita.com/a-yonenaga/items/18c9aaf67abf1f897e72 では、ES6で開発中のプロジェクトのTypeScriptの移行に着手した。この移行作業中に、moment-duration-formatを使用しているクラスでコンパイルエラーが発生した。

moment-duration-formatは、時間を扱うライブラリmoment.js( https://momentjs.com )内の、期間を表現するクラスdurationにフォーマット出力の機能を追加するライブラリ。

エラーメッセージ

Property 'format' does not exist

EditableProgram_ts_—_gachi-taite-designer-web.png

TypeScriptではうまくmoment.Durationに機能をうまく追加してくれない(というより、存在するはずだが呼ぶことができない?)らしい。

解決策

StackOverflowにあった。
https://stackoverflow.com/questions/43058807/how-to-use-moment-duration-format-in-typescript

使っている.tsファイル内で、moment.Durationを拡張したDurationを作ってやる。

moment-duration-formatを使用するファイル内でのinterface宣言
interface Duration extends moment.Duration {
    format: (template?: string, precision?: number, settings?: DurationSettings) => String
}

interface DurationSettings {
    forceLength:boolean
    precision: number
    template: string
    trim: boolean | 'left' | 'right'
}
変更前
const programLengthHHmm = moment.duration(program.lengthMinute, 'minutes').format('HH:mm', {trim: false})

moment.durationをDuration型にキャストすることで、format()関数が呼べるようになった。
precisionやtrim:falseの渡し方が変わったので、その部分の対応も加えている。

変更後
const durationSettings = {trim: false} as DurationSettings

const programLengthDuration = (moment.duration(program.lengthMinute, 'minutes') as Duration)
const programLengthHHmm = programLengthDuration.format('HH:mm', null, durationSettings) as string
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0