mcpField
T
typescript-refactoring-patterns

typescript-refactoring-patterns

github.com/autohandai開発1159 回インストール15 週間前に更新
リポジトリ

typescript-refactoring-patterns について

typescript-refactoring-patterns は、TypeScript のリファクタリングと型安全性に関するリファレンススキルです。型の絞り込み、バリアントのモデル化、ドメイン値の検証パターンを示します。

主な機能

  1. 01型ガードと判別可能なユニオン
  2. 02const アサーションとジェネリック制約
  3. 03ドメイン検証用のブランド型
  4. 04多態性による switch のリファクタリング
  5. 05安全でない型付けのコードスメル検出

活用シーン

  1. 01型アサーションを型ガードに置き換える
  2. 02相互排他的な状態をモデル化する
  3. 03ドメイン固有の文字列値を検証する

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/autohandai/community-skills --skill typescript-refactoring-patterns

インストール後、Claude Code で/typescript-refactoring-patternsを入力して読み込まれたか確認します。

詳細

TypeScript のリファクタリングパターン

基本原則

  1. 型アサーションよりも型の絞り込み - as キャストの代わりに、型ガードと判別可能なユニオンを使用します
  2. リテラルには const アサーション - 不変のリテラル型には as const を使用します
  3. ジェネリック制約 - any よりも extends 制約を優先します
  4. ブランド型 - ドメイン固有の検証にはブランド型を使用します

リファクタリングパターン

判別可能なユニオンを抽出する

複数のブールフラグがある場合は、判別可能なユニオンにリファクタリングします。

// Before
interface User {
  isAdmin: boolean;
  isGuest: boolean;
  permissions?: string[];
}

// After
type User =
  | { role: 'admin'; permissions: string[] }
  | { role: 'guest' }
  | { role: 'member'; permissions: string[] };
条件分岐をポリモーフィズムに置き換える

型に基づく switch 文がある場合は、ストラテジーパターンを使用します。

// Before
function process(item: Item) {
  switch (item.type) {
    case 'a': return processA(item);
    case 'b': return processB(item);
  }
}

// After
const processors: Record<ItemType, (item: Item) => Result> = {
  a: processA,
  b: processB,
};
const process = (item: Item) => processors[item.type](item);
型ガードを抽出する

型を絞り込む際は、再利用可能な型ガードを作成します。

function isNonNullable<T>(value: T): value is NonNullable<T> {
  return value !== null && value !== undefined;
}

// Usage
const items = array.filter(isNonNullable);
検証にブランド型を使用する

ブランド型を使って、プリミティブ型への過度な依存を防ぎます。

type UserId = string & { readonly brand: unique symbol };
type Email = string & { readonly brand: unique symbol };

function createUserId(id: string): UserId {
  if (!isValidUuid(id)) throw new Error('Invalid user ID');
  return id as UserId;
}

コードの問題を見つけるポイント

次のパターンに注意し、リファクタリングします。

  • any 型(unknown と型ガードに置き換えます)
  • 非 null アサーション !(適切なチェックを追加します)
  • 型アサーション as(型ガードを使用します)
  • オプショナルチェーンの過剰な使用 ?.?.?.(データ構造を見直します)
  • 検証なしのインデックスシグネチャ

すぐにできる改善

  1. tsconfig で strict: true を有効にします
  2. 型を拡大せずにチェックするには satisfies を使用します
  3. readonly 配列とオブジェクトを優先します
  4. 外部データには unknown を使用し、境界で検証します

コメント