TypeScript with Claude Code
Learn about typescript using Claude Code. Practical tips and code examples included.
ユーティリティ型で型定義を効率化する
TypeScriptのユーティリティ型は、既存の型を変換して新しい型を作る仕組みです。Claude Codeは標準ユーティリティ型の活用はもちろん、プロジェクト固有のカスタムユーティリティ型の設計にも力を発揮します。
標準ユーティリティ型の実践活用
Claude Codeに「型を変換して」と伝えるだけで、適切なユーティリティ型を選択してくれます。
> User型からフォーム用の型を作って。
> id, createdAt, updatedAtは除外し、残りはすべてオプショナルに。
interface User {
id: string;
name: string;
email: string;
role: "admin" | "editor" | "viewer";
bio: string;
createdAt: Date;
updatedAt: Date;
}
// Claude Codeが生成する型
type UserFormData = Partial<Omit<User, "id" | "createdAt" | "updatedAt">>;
// 新規作成時は必須フィールドを指定
type CreateUserData = Required<Pick<User, "name" | "email" | "role">> &
Partial<Pick<User, "bio">>;
Record型とMapped Typesの活用
設定やマッピング定義にはRecord型が便利です。
// ロールごとの権限マッピング
type Permission = "read" | "write" | "delete" | "admin";
type Role = "admin" | "editor" | "viewer";
const rolePermissions: Record<Role, Permission[]> = {
admin: ["read", "write", "delete", "admin"],
editor: ["read", "write"],
viewer: ["read"],
};
// フォームフィールドのバリデーションルール
type ValidationRule<T> = {
[K in keyof T]: {
required?: boolean;
minLength?: number;
maxLength?: number;
pattern?: RegExp;
validate?: (value: T[K]) => string | true;
};
};
const userValidation: ValidationRule<CreateUserData> = {
name: { required: true, minLength: 2, maxLength: 50 },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
role: { required: true },
bio: { maxLength: 500 },
};
カスタムユーティリティ型の設計
Claude Codeにプロジェクト固有のユーティリティ型を依頼すると、適切な設計を提案してくれます。
> APIレスポンスで使うカスタムユーティリティ型を設計して。
> ページネーション、ソート、フィルタに対応して。
// ページネーション付きレスポンス
type Paginated<T> = {
items: T[];
total: number;
page: number;
perPage: number;
totalPages: number;
hasNext: boolean;
hasPrev: boolean;
};
// ソート可能なフィールドを抽出
type SortableKeys<T> = {
[K in keyof T]: T[K] extends string | number | Date ? K : never;
}[keyof T];
type SortParams<T> = {
sortBy: SortableKeys<T>;
sortOrder: "asc" | "desc";
};
// フィルタ型を自動生成
type FilterParams<T> = {
[K in keyof T]?: T[K] extends string
? { contains?: string; equals?: string; startsWith?: string }
: T[K] extends number
? { gte?: number; lte?: number; equals?: number }
: T[K] extends Date
? { after?: Date; before?: Date }
: T[K];
};
// 組み合わせて使う
type ListQuery<T> = Partial<SortParams<T>> &
FilterParams<T> & {
page?: number;
perPage?: number;
};
// Usage example
type UserListQuery = ListQuery<User>;
// => { sortBy?: "name" | "email" | "createdAt" | ..., page?: number, ... }
Extract / Exclude で型を絞り込む
ユニオン型からの型の抽出・除外もClaude Codeに依頼すると素早く実装できます。
type Event =
| { type: "click"; x: number; y: number }
| { type: "keypress"; key: string; code: number }
| { type: "scroll"; scrollY: number }
| { type: "resize"; width: number; height: number };
// 特定のイベントだけ抽出
type MouseEvent = Extract<Event, { type: "click" }>;
// => { type: "click"; x: number; y: number }
// イベントハンドラーの型を自動生成
type EventHandlers = {
[E in Event as `on${Capitalize<E["type"]>}`]: (event: E) => void;
};
// => { onClick: (event: ...) => void; onKeypress: ... }
Template Literal Typesとの組み合わせ
TypeScript 4.1以降のTemplate Literal Typesをユーティリティ型と組み合わせるパターンです。
type CSSProperty = "margin" | "padding" | "border";
type Direction = "top" | "right" | "bottom" | "left";
type CSSDirectionalProperty = `${CSSProperty}-${Direction}`;
// => "margin-top" | "margin-right" | ... | "border-left"
// CSSスタイルオブジェクトの型
type StyleObject = Partial<Record<CSSDirectionalProperty, string | number>>;
const style: StyleObject = {
"margin-top": 16,
"padding-left": "1rem",
};
実践的な使い方のポイント
Claude Codeにユーティリティ型を依頼する際のコツです。
- 変換前後の型を明示する - 「User型からこういう型を作って」と伝える
- 用途を説明する - 「フォーム用」「APIレスポンス用」など文脈を示す
- 既存の型定義を共有する - 元になる型を見せると精度が上がる
Summary
ユーティリティ型を使いこなすことで、型定義の重複を減らし保守性の高いコードベースを実現できます。Claude Codeは複雑な型変換も一発で生成してくれるので、型パズルに悩む時間を大幅に削減できます。
ジェネリクスの基礎はTypeScriptジェネリクス実践ガイドを、バリデーションとの連携はZodバリデーション実践ガイドを参照してください。TypeScript公式のユーティリティ型リファレンスも参考になります。
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Key commands, shortcuts, and prompt examples on a single printable page.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
Creating Custom Slash Commands in Claude Code — Tailor Your Workflow
Learn how to create custom slash commands in Claude Code. Covers file placement, arguments, and automating frequent tasks with practical code examples.
10 Tips to Triple Your Productivity with Claude Code
Learn about 10 tips to triple your productivity using Claude Code. Practical tips and code examples included.
Canvas/WebGL Optimization with Claude Code
Learn about Canvas/WebGL optimization using Claude Code. Practical tips and code examples included.