LoginSignup
1
4

More than 5 years have passed since last update.

Typescript+Vue.jsにおいて、vue-class-componentを使わずにmixins先のmethods, dataを推論できない問題

Last updated at Posted at 2018-02-27

typescript + vueにおいて、クラスベースの書き方(= vue-class-component)を使わずにmixin先を推論する方法がどうしてもわからず頭を抱えていたが、一旦の回避策を得たのでそのご紹介。

なお日記に書いた内容の拡充版です。

前提

  • typescript 2.7 + Vue.js 2.5
  • vue-class-componentは使いたくないので使わない

問題

mixinした先のメソッドやデータに対してthisが推論してくれない。この問題がどうしても解決できなかった。

もうわからなさすぎたのでvue forumに質問したら回答をもらえた。(感謝)

結論

今はmixin先のdata, methods, props, comuptedなどを推論することはできない。
なので対応策としては2つ。

1. thisをanyにキャストする

フォーラムでもらった回答がこちら。全く考えもつかなかった...
確かにこれが一番手軽で良さそう。

console.log(this.msg)
to
console.log((this as any).msg)

(少し行儀は悪いけど)困ったらanyにキャストすればいい。

2. (冗長だが) 局所的にVue interfaceを拡張する

自分で試していたのはこちら。mixin先をいちいち見なくとも何が生えているのか見えるのはいいが、同じものを二度書きするのが冗長で辛い。また型を間違えると大変なことになりそう

interface Vue {

  // @mixin HogeMixin
  hogeMixinSomeData: string       // this is sample.
  hogeMixinSomeMethod: () => void // this is sample.
  // ... 他にもdata, methods, computedなど記述する

  // @mixin GehoMixin
  gehoMixinSomeData: number
  gehoMixinSomeMethod: () => void
}

Vue.extend({
  mixins: [HogeMixin, GehoMixin]
  methods: {
    doSomething () {
      console.log(this.hogeMixinSomeData) // ok
      console.log(this.gehoMixinSomeData) // ok
      this.hogeMixinSomeMethod()          // ok
      this.gehoMixinSomeMethod()          // ok
    }
  }
})

所感

mixin先まで推論できるようになると嬉しいなぁ。

追記

...!!!

ありがとうございます :bow:
さっそく試してみます。

1
4
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
4