少し前ですが、2019/4/5 に Nuxt.js v2.6.0 がリリース されました!
Nuxt.js + TypeScript な環境である自分のプロジェクトでも、v2.4.3 から v2.6.0 にバージョンアップしたのですが、その時に型周りでハマったのでメモとして残しておきます。
型のエラーが大量に発生...
yarn add nuxt で Nuxt.js を最新版にバージョンアップし、yarn dev で開発環境を起動したところ、Type 'Vue' is not assignable というエラーが大量のコンポーネントで発生しました。
error in /path/to/my-project/src/components/Organisms/HogeComponent/HogeComponent.ts
ERROR in /path/to/my-project/src/components/Organisms/HogeComponent/HogeComponent.ts(4,27):
TS2345: Argument of type '{ components: { FugaComponent: Vue; }; props: { headers: { type: () => any[]; required: true; }; items: { type: () => any[]; required: true; }; buttonText: { type: StringConstructor; default: string; }; buttonTo: { type: StringConstructor; default: string; }; showButton: { ...; }; defaultSort: { ...; }; error: { ...; ...' is not assignable to parameter of type 'ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<string, any>>'.
Types of property 'components' are incompatible.
Type '{ FugaComponent: Vue; }' is not assignable to type '{ [key: string]: VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...>; }'.
Property 'FugaComponent' is incompatible with index signature.
Type 'Vue' is not assignable to type 'VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...>'.
Type 'Vue' is not assignable to type 'AsyncComponentFactory<any, any, any, any>'.
「components に登録しているコンポーネントの型がおかしいよ」って意味のようなのですが、バージョンアップする前は問題ありませんでした。
原因を調べる
HogeComponent.ts では FugaComponent を components に登録しています。
import FugaComponent from 'components/Organisms/FugaComponent';
import Vue from 'vue';
export default Vue.extend({
components: { FugaComponent },
...
});
先程のエラーメッセージによると、「components に割り当てられるのは VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...> のいずれかの型だよ」ということみたいです。
ですが、FugaComponent は Vue 型です。上記のいずれの型でもないからエラーになったみたいです。
vue-shims.d.ts の修正で直った
FugaComponent が Vue 型なのは、vue-shims.d.ts で *.vue が拡張子のファイルを import したらそれを Vue 型とみなすようにしているからです。
これを「VueConstructor<Vue> 型にすれば直るのでは?」と考え、以下のように修正しました。
declare module '*.vue' {
import { VueConstructor } from 'vue';
const d: VueConstructor;
export default d;
}
すると大量に出ていたエラーは嘘のように消えました!
正直理由はよくわかっていないのですが、ひとまず問題なさそうなのでこの方法でエラーを回避していますmm