目次

目次

【備忘録】Vue3プロジェクトでTypeScriptの型チェックを行うとエラーが重複して出力されてしまう

アバター画像
坂本彩乃
アバター画像
坂本彩乃
最終更新日2024/11/22 投稿日2024/11/22

はじめに

フロントエンド開発においてTypeScriptを扱うことによる恩恵は色々ありますが、その中でも 型チェックを行えることは大きな利点です。 しかし、Vue3プロジェクトで型チェックを行う際に、同じ箇所でエラーが重複して出力される問題に悩まされたため、解決方法を備忘録として残しておきます。

開発環境

  • TypeScript v5.4.5
  • Vue v3.4.29
  • Vite v5.4.2

現象

以下のnpmコマンドを実行した際、エラーが重複して出力されてしまいました。

# package.json(抜粋)

"scripts": {
  "type-check": "vue-tsc --build --force"
}

出力例

参考までに、実際に出力されたエラーを記載しておきます。 以下のように、わざと型エラーが発生するコードを用意しました。

# test.vue
function triggerTypeError() {
  let message: number = 42;
  message = 'これは文字列です';
}

triggerTypeError();

リンターの実行結果は下記のとおりです。

test.vue:4:3 - error TS2322: Type 'string' is not assignable to type 'number'.

4   message = 'これは文字列です';
     ~~~~~~~

test.vue:4:3 - error TS2322: Type 'string' is not assignable to type 'number'.

4   message = 'これは文字列です';
     ~~~~~~~

Found 2 errors.

ディレクトリ・ファイル構成

こちらも参考までにディレクトリ・ファイル構成を記載しておきます。

root/
├── src/
├── public/
├── .eslintrc.cjs
├── .eslintignore
├── .prettierrc.json
├── .stylelintignore
├── .vscode/
├── index.html
├── package.json
├── package-lock.json
├── stylelint.config.mjs
├── tsconfig.json
├── tsconfig.app.json
├── tsconfig.node.json
├── tsconfig.vitest.json
├── vite.config.ts
└── vitest.config.ts

原因

TypeScriptの設定ファイルであるtsconfig.jsonが複数のtsconfigを参照しているため、 vue-tsc --buildを実行すると同じファイルが複数のtsconfigでビルドされることによってエラーが重複しているようでした。 各tsconfigをいじった覚えは特に無く、環境構築(create-vue)時に自動的に生成された設定であったため盲点でした。

# tsconfig.json

{
  "files": [],
  "references": [
    {
      "path": "./tsconfig.node.json"
    },
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ]
}

ということで各tsconfigを確認してみました。 そのうちの一つであるtsconfig.vitest.jsonを見ると、以下のようにextendsでtsconfig.app.jsonが継承されていました。

# tsconfig.vitest.json

{
  "extends": "./tsconfig.app.json",
  "exclude": [],
  "compilerOptions": {
    "composite": true,
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.vitest.tsbuildinfo",

    "lib": [],
    "types": ["node", "jsdom"]
  }
}

このため、型チェックを行う際はtsconfig.vitest.jsonとtsconfig.node.jsonだけを指定すれば問題が解決できそうです。

対象法

上記を踏まえてnpmコマンドを以下のように修正しました。

# package.json(抜粋)

"scripts": {
  "type-check": "vue-tsc --build --force tsconfig.vitest.json tsconfig.node.json"
}

参考にしたもの

アバター画像

坂本彩乃

目次