0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

段階的にstrictモードを有効化するTypeScript設定のコツ

0
Posted at

TypeScript の strict オプションは、コードの安全性を高める強力な機能ですが、いきなりすべてを有効にするとコンパイルエラーが大量に出て、初心者は挫折しがちです。そこで、段階的に strict を有効化する手順と、tsconfig.json の設定順序のポイントを解説します。

1. まずはベースラインを固める

strict 系のオプションは、noImplicitAny、strictNullChecks、strictPropertyInitialization など複数に分かれています。まずはプロジェクト全体で 型チェックが有効 になるよう、strict 以外の基本設定だけを書き込みます。

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true
  }
}

この状態で npm run build が通ることを確認しましょう。

2. noImplicitAny を先にオン

any が暗黙的に許容されると、型安全の恩恵が薄れます。まずは noImplicitAny: true を追加します。

{
  "compilerOptions": {
    // 前述の設定に加えて
    "noImplicitAny": true
  }
}

この段階で出てくるエラーは、関数の引数や変数に型が付いていない箇所です。any を明示的に書くか、適切な型を付与して解消します。

3. strictNullChecks で null/undefined の安全性を確保

次に strictNullChecks: true を有効にします。これにより null や undefined が許容される場所が限定され、実行時エラーを防げます。

{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true
  }
}

ここで出るエラーは、変数が undefined になる可能性があるケースです。?(オプショナルチェーン)や型ガードで対処しましょう。

4. strictPropertyInitialization と strictBindCallApply

クラスのプロパティがコンストラクタで必ず初期化されているかチェックする strictPropertyInitialization と、bind・call・apply の型安全性を高める strictBindCallApply を順に有効にします。

{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true
  }
}

クラスを書き直す機会になるので、初心者でも設計を見直す良いタイミングです。

5. 最後に strict フラグでまとめて有効化

上記の項目がすべてクリアできたら、strict: true を設定して残りの strict 系オプションを一括で有効にします。tsconfig.json の最上位に置くと、設定が見やすくなります。

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true,
    "strict": true
  }
}

まとめ

  1. 基本設定だけでビルドが通ることを確認
  2. noImplicitAny → strictNullChecks → strictPropertyInitialization / strictBindCallApply の順にオン
  3. 最後に strict: true で総仕上げ

この段階的アプローチなら、エラーの量が急増せず、学習コストを抑えながら安全なコードベースを構築できます。実務でも CI パイプラインに組み込むことで、プルリクエストごとに型チェックが走り、品質が保たれます。

詳しい手順はこちら → https://felixstudio0.gumroad.com/?utm_source=qiita&utm_medium=github_actions&utm_campaign=2026-q1&utm_content=qiita-footer

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?