TypeScript型安全性設定 - mrstsgk/daycare-app-portfolio GitHub Wiki

このプロジェクトでは、コードの品質と型安全性を向上させるために厳格なTypeScript設定を適用しています。

ESLint TypeScriptルール

主要なルール

@typescript-eslint/no-explicit-any (error)

  • 目的: any型の使用を禁止し、適切な型定義を強制
  • 効果: 型安全性の向上、実行時エラーの減少
// ❌ エラー
function processData(data: any) {
  return data.someProperty;
}

// ✅ 正しい
function processData(data: { someProperty: string }) {
  return data.someProperty;
}

@typescript-eslint/no-unsafe-* (warning)

  • no-unsafe-assignment: 安全でない代入を警告
  • no-unsafe-member-access: 安全でないメンバーアクセスを警告
  • no-unsafe-call: 安全でない関数呼び出しを警告
  • no-unsafe-return: 安全でない戻り値を警告

@typescript-eslint/prefer-nullish-coalescing (error)

  • 目的: ||の代わりに??演算子の使用を推奨
  • 効果: null/undefinedの処理をより安全に
// ❌ エラー
const baseUrl = process.env.API_URL || "http://localhost:3000";

// ✅ 正しい
const baseUrl = process.env.API_URL ?? "http://localhost:3000";

@typescript-eslint/prefer-optional-chain (error)

  • 目的: オプショナルチェーン(?.)の使用を推奨
// ❌ エラー
if (user && user.profile && user.profile.name) {
  console.log(user.profile.name);
}

// ✅ 正しい
if (user?.profile?.name) {
  console.log(user.profile.name);
}

TypeScript Compiler設定

tsconfig.json の厳格な設定

{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    // 段階的導入予定
    "noUncheckedIndexedAccess": false,
    "exactOptionalPropertyTypes": false,
    "noPropertyAccessFromIndexSignature": false
  }
}

各設定の説明

  • noImplicitAny: 暗黙的なany型を禁止
  • noImplicitReturns: 関数内のすべてのパスで戻り値を要求
  • noImplicitThis: 暗黙的なthisの型を禁止

段階的導入

一部のルールは段階的に導入されます:

  1. 現在: 基本的な型安全性ルールを適用
  2. 第2段階: noUncheckedIndexedAccessを有効化
  3. 第3段階: exactOptionalPropertyTypesを有効化

any型を使用する必要がある場合

やむを得ずany型を使用する場合は、ESLintの無効化コメントを使用してください:

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function legacyApiCall(data: any) {
  // 外部ライブラリとの互換性が必要な場合など
  return externalLibrary.process(data);
}

型定義のベストプラクティス

1. インターフェースの使用

interface User {
  id: number;
  name: string;
  email?: string; // オプショナル
}

2. Union型の活用

type Status = 'loading' | 'success' | 'error';

3. ジェネリクスの使用

function processArray<T>(items: T[]): T[] {
  return items.filter(Boolean);
}

トラブルシューティング

よくあるエラーと解決方法

  1. any型エラー: 適切な型定義を追加
  2. Nullish coalescing警告: ||??に変更
  3. Optional chain警告: &&チェーンを?.に変更

設定の確認

# ESLintチェック
npm run lint

# フォーマット
npm run format

# 両方を実行
npm run lint:format

この設定により、より安全で保守性の高いTypeScriptコードを書くことができます。