kurosame’s diary

フロントエンド中心です

@nuxtjs/moment の型定義

Vuex の型定義を拡張して、@nuxtjs/moment の型を追加してあげようっていうだけの記事です

まずは前提として、Nuxt.js では store ディレクトリ配下が Vuex になっており、
store 配下にファイルを作成して、そのファイル内で actions オブジェクトを export すれば、
ファイル名/ActionTypeという指定で Vue のコンポーネントとかからアクションを dispatch できる

この actions オブジェクト内で this を参照すると、this はStore<S>という型になっている

今回の問題は@nuxtjs/momentStore<S>に含まれていないので、以下のように型エラーになってしまう

f:id:kurosame-th:20191025183646p:plain

面倒なら this を any にキャストしても良いと思うが、一応以下の型定義をプロジェクトルートとかに置けば、エラーは無くなる

// @types/@nuxtjs-moment.d.ts
import { Moment, MomentFormatSpecification, MomentInput } from 'moment'

declare module 'vuex/types/index' {
  interface Store<S> {
    $moment(
      input?: MomentInput,
      format?: MomentFormatSpecification,
      language?: string,
      strict?: boolean
    ): Moment
  }
}

追記

Vue コンポーネントから@nuxtjs/momentを参照する場合は、以下も追加しておく

// @types/@nuxtjs-moment.d.ts
import { Moment, MomentFormatSpecification, MomentInput } from 'moment'

declare module 'vue/types/vue' {
  interface Vue {
    $moment(
      input?: MomentInput,
      format?: MomentFormatSpecification,
      language?: string,
      strict?: boolean
    ): Moment
  }
}

今回実装したコード

GitHub - kurosame/event-search: Event search App with Nuxt.js