tsconfig は『型安全の入り口』
TypeScript の効果は tsconfig.json の設定で大きく変わります。本記事では編集部の視点で、現代的な厳格設定を公開情報をもとに整理します。TypeScript 上級 もご参考に。
strict mode の効果
(1) noImplicitAny:暗黙の any 禁止。(2) strictNullChecks:null/undefined 厳格扱い。(3) strictFunctionTypes:関数型の bivariance 禁止。(4) strictBindCallApply:bind/call/apply の型安全。(5) noImplicitThis:this の型推論。strict: true で全部有効になります。
追加で有効化すべき設定
(1) noUncheckedIndexedAccess:配列/オブジェクトアクセスを undefined 可能に。(2) exactOptionalPropertyTypes:optional の厳密化。(3) noImplicitOverride:override 明示。(4) noFallthroughCasesInSwitch:switch の漏れ防止。(5) noUnusedLocals/Parameters:未使用の警告。いずれも安全性を一段上げる設定です。
モジュール設定
(1) target: "ES2022":モダンブラウザ向け。(2) module: "NodeNext":Node.js 用。(3) moduleResolution: "Bundler":Vite/webpack 等。(4) esModuleInterop: true:CommonJS との相互運用。(5) verbatimModuleSyntax: true:import type の明示。
パス設計
(1) baseUrl + paths:エイリアス設定。(2) @/components:プロジェクト内パス。(3) Monorepo:tsconfig.base.json で共有。(4) project references:型解決の高速化。(5) VS Code 連携:自動補完。Monorepo 設計 もご参考に。
ビルド最適化
(1) incremental: true:差分コンパイル。(2) composite: true:project references。(3) tsBuildInfoFile:キャッシュ場所。(4) skipLibCheck: true:型チェック高速化(注意点あり)。(5) isolatedModules: true:esbuild/swc 互換。CI/CD 実践 もご参考に。
新規プロジェクトの推奨設定
(1) extends:@tsconfig/strictest 等の共有設定。(2) include/exclude:明示的に絞る。(3) jsx:React 17+ なら "react-jsx"。(4) lib:環境別に明示。(5) types:自動取込制御。
失敗しがちなパターン
(1) strict 無効化:型安全性喪失。(2) any 多用:型推論の恩恵喪失。(3) moduleResolution 古いまま:エラー多発。(4) skipLibCheck で型違反見落とし。(5) incremental 無効:CI 時間長期化。対策は、(1)新規はstrict、(2)unknown 経由、(3)Bundler/NodeNext、(4)定期的なfull check、(5)incremental 有効、です。