mcpField
T
typescript-best-practices

typescript-best-practices

github.com/jwynia開発180603 回インストール35 週間前に更新
リポジトリ

typescript-best-practices について

typescript-best-practicesは、TypeScriptの作成やレビューを行うエージェント向けのコーディングガイドです。型安全性や不変性、エラー処理、コード構成の指針に加え、分析や生成、スキャフォールディング用スクリプトを備えています。

主な機能

  1. 01型安全性と不変性の重視
  2. 02エラー処理とモジュール設計の指針
  3. 03TypeScriptコードの分析スクリプト
  4. 04JSONデータからの型生成
  5. 05構造化モジュールのスキャフォールディング

活用シーン

  1. 01新しいTypeScriptコードの生成
  2. 02TypeScriptファイルの品質レビュー
  3. 03JavaScriptからTypeScriptへのリファクタリング
  4. 04モジュール、サービス、コンポーネントの作成

インストール

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

$npx skills add https://github.com/jwynia/agent-skills --skill typescript-best-practices

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

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

assets/templates/
module-template.ts.md
service-template.ts.md
assets/tsconfig-presets/
recommended.json
strict.json
references/anti-patterns/
common-mistakes.md
references/architecture/
api-design.md
project-structure.md
references/patterns/
async-patterns.md
error-handling.md
functional-patterns.md
module-patterns.md
references/type-system/
advanced-types.md
type-guards.md
utility-types.md
scripts/
analyze.ts
generate-types.ts
scaffold-module.ts

詳細

TypeScript のベストプラクティス

AI エージェントが高品質な TypeScript コードを作成できるようにします。このスキルでは、コーディング標準、アーキテクチャパターン、分析およびスキャフォールディング用のツールを紹介します。

このスキルを使用する場面

次の場合にこのスキルを使用してください:

  • 新しい TypeScript コードを生成するとき
  • TypeScript ファイルの品質上の問題をレビューするとき
  • 新しいモジュール、サービス、コンポーネントを作成するとき
  • JavaScript を TypeScript にリファクタリングするとき
  • TypeScript のパターンや型について質問に答えるとき
  • API やインターフェースを設計するとき

次の場合はこのスキルを使用しないでください:

  • 純粋な JavaScript(TypeScript なし)を扱うとき
  • 実行時エラーをデバッグするとき(デバッグツールを使用してください)
  • フレームワーク固有のパターンを扱うとき(React、Vue など。フレームワーク用スキルを使用してください)

基本原則

1. 型安全性を最優先する

コンパイル時のエラー検出を最大限に高めます:

// Prefer unknown over any for unknown types
function processInput(data: unknown): string {
  if (typeof data === "string") return data;
  if (typeof data === "number") return String(data);
  throw new Error("Unsupported type");
}

// Explicit return types for public APIs
export function calculateTotal(items: ReadonlyArray<Item>): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// Use const assertions for literal types
const CONFIG = {
  mode: "production",
  version: 1,
} as const;
2. デフォルトで不変にする

意図しない変更を防ぎます:

// Use readonly for object properties
interface User {
  readonly id: string;
  readonly email: string;
  name: string; // Only mutable if intentional
}

// Use ReadonlyArray for collections
function processItems(items: ReadonlyArray<Item>): ReadonlyArray<Result> {
  return items.map(transform);
}

// Prefer spreading over mutation
function updateUser(user: User, name: string): User {
  return { ...user, name };
}
3. 型を使ったエラー処理

エラー処理には型システムを使用します:

// Result type for recoverable errors
type Result<T, E = Error> =
  | { success: true; value: T }
  | { success: false; error: E };

// Typed error classes
class ValidationError extends Error {
  constructor(
    message: string,
    readonly field: string,
    readonly code: string
  ) {
    super(message);
    this.name = "ValidationError";
  }
}

// Function with Result return type
function parseConfig(input: string): Result<Config, ValidationError> {
  try {
    const data = JSON.parse(input);
    if (!isValidConfig(data)) {
      return {
        success: false,
        error: new ValidationError("Invalid config", "root", "INVALID_FORMAT"),
      };
    }
    return { success: true, value: data };
  } catch {
    return {
      success: false,
      error: new ValidationError("Parse failed", "root", "PARSE_ERROR"),
    };
  }
}
4. コードの構成

保守しやすいコード構成にします:

// One concept per file
// user.ts - User type and related utilities
export interface User {
  readonly id: string;
  readonly email: string;
  readonly createdAt: Date;
}

export function createUser(email: string): User {
  return {
    id: crypto.randomUUID(),
    email,
    createdAt: new Date(),
  };
}

// Explicit exports (no barrel file wildcards)
// index.ts
export { User, createUser } from "./user.ts";
export { validateEmail } from "./validation.ts";

クイックリファレンス

カテゴリ推奨避ける
不明な型unknownany
コレクションReadonlyArray<T>入力に対する T[]
オブジェクトReadonly<T>デフォルトで変更可能にすること
null チェックオプショナルチェーン ?.!= null
型の絞り込み型ガードas アサーション
戻り値の型エクスポート時に明示するエクスポート時に推論に任せる
列挙型文字列リテラルのユニオン数値列挙型
インポート名前付きインポートデフォルトインポート
エラーResult 型フロー制御のためにスローすること
ループfor...of、.map()配列に対する for...in

コード生成ガイドライン

TypeScript コードを生成する際は、次のパターンに従ってください:

モジュール構成
/**
 * Module description
 * @module module-name
 */

// === Types ===
export interface ModuleOptions {
  readonly setting: string;
}

export interface ModuleResult {
  readonly data: unknown;
}

// === Constants ===
const DEFAULT_OPTIONS: ModuleOptions = {
  setting: "default",
};

// === Implementation ===
export function processData(
  input: unknown,
  options: Partial<ModuleOptions> = {}
): ModuleResult {
  const opts = { ...DEFAULT_OPTIONS, ...options };
  // Implementation
  return { data: input };
}
関数の設計
// Pure functions preferred
function transform(input: Input): Output {
  // No side effects, same input = same output
  return { ...input, processed: true };
}

// Explicit parameter types
function fetchUser(id: string, options?: FetchOptions): Promise<User> {
  // Implementation
}

// Use function overloads for complex signatures
function parse(input: string): ParsedData;
function parse(input: Buffer): ParsedData;
function parse(input: string | Buffer): ParsedData {
  // Implementation
}
インターフェースの設計
// Prefer interfaces for object shapes
interface UserData {
  readonly id: string;
  readonly email: string;
}

// Use type for unions and intersections
type UserRole = "admin" | "user" | "guest";
type AdminUser = UserData & { readonly role: "admin" };

// Document with JSDoc
/**
 * Configuration for the API client
 * @property baseUrl - The base URL for API requests
 * @property timeout - Request timeout in milliseconds
 */
interface ApiConfig {
  readonly baseUrl: string;
  readonly timeout?: number;
}

よくあるアンチパターン

コードを生成する際は、次のパターンを避けてください:

アンチパターン問題解決策
any 型型チェックが無効になりますunknown を使い、型を絞り込む
as アサーション実行時エラーにつながります型ガードを使う
非 null アサーション !null ポインターエラーにつながりますオプショナルチェーン ?.
変更可能な引数予期しない変更が起こりますReadonly<T>
マジック文字列タイポが発生し、オートコンプリートも使えません文字列リテラル型
ゴッドクラステストや保守が困難になります単一責任
循環依存ビルド時や実行時の問題につながります依存性逆転
インデックスシグネチャ型情報が失われます明示的なプロパティ

詳しい例については、references/anti-patterns/common-mistakes.md を参照してください。

スクリプトのリファレンス

analyze.ts

品質上の問題がないか TypeScript コードを分析します:

deno run --allow-read scripts/analyze.ts <path> [options]

Options:
  --strict        Enable all checks
  --json          Output JSON for programmatic use
  --fix-hints     Show suggested fixes

Examples:
  # Analyze a file
  deno run --allow-read scripts/analyze.ts ./src/utils.ts

  # Analyze directory with strict mode
  deno run --allow-read scripts/analyze.ts ./src --strict

  # JSON output for CI
  deno run --allow-read scripts/analyze.ts ./src --json
generate-types.ts

JSON データから TypeScript 型を生成します:

deno run --allow-read --allow-write scripts/generate-types.ts <input> [options]

Options:
  --name <name>   Root type name (default: inferred)
  --output <path> Output file path
  --readonly      Generate readonly types
  --interface     Use interface instead of type

Examples:
  # Generate from JSON file
  deno run --allow-read scripts/generate-types.ts ./data.json --name Config

  # Generate readonly interface
  deno run --allow-read --allow-write scripts/generate-types.ts ./api-response.json \
    --interface --readonly --output ./types/api.ts
scaffold-module.ts

適切な構成の TypeScript モジュールを作成します:

deno run --allow-read --allow-write scripts/scaffold-module.ts [options]

Options:
  --name <name>   Module name (required)
  --path <path>   Target directory (default: ./src)
  --type <type>   Type: service, util, component
  --with-tests    Include test file

Examples:
  # Create a utility module
  deno run --allow-read --allow-write scripts/scaffold-module.ts \
    --name "string-utils" --type util

  # Create a service with tests
  deno run --allow-read --allow-write scripts/scaffold-module.ts \
    --name "user-service" --type service --with-tests

追加リソース

型システムの詳細解説
  • references/type-system/advanced-types.md - ジェネリクス、条件型、マップ型
  • references/type-system/type-guards.md - 型を絞り込む手法
  • references/type-system/utility-types.md - 組み込みユーティリティ型
パターンガイド
  • references/patterns/error-handling.md - Result 型、型付きエラー
  • references/patterns/async-patterns.md - Async/await のベストプラクティス
  • references/patterns/functional-patterns.md - 不変性、合成
  • references/patterns/module-patterns.md - エクスポート、依存性注入
アーキテクチャ
  • references/architecture/project-structure.md - ディレクトリ構成
  • references/architecture/api-design.md - インターフェース設計、バージョニング
テンプレート
  • assets/templates/module-template.ts.md - モジュールのスターターテンプレート
  • assets/templates/service-template.ts.md - サービスクラスのテンプレート
  • assets/tsconfig-presets/strict.json - 最大限に厳格な設定
  • assets/tsconfig-presets/recommended.json - バランスの取れたデフォルト設定

コメント