typescript について
TypeScript 開発者向けのコーディングガイドスキルです。型定義、インターフェース設計、型安全性のパターンを、コードの作成やレビュー時に参照できます。
主な機能
- 01const オブジェクトからユニオン型を導出
- 02インターフェースをフラットに保つ
- 03any の使用を避ける
- 04ユーティリティ型とジェネリクスの活用
- 05型ガードと型インポートの使用
活用シーン
- 01ステータスなどのリテラル型の定義
- 02ユーザーデータ構造の設計
- 03未知の入力の解析と検証
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ gentleman-programming/ gentleman-skills --skill typescriptインストール後、Claude Code で/typescriptを入力して読み込まれたか確認します。
詳細
Const 型パターン(必須)
// ✅ ALWAYS: Create const object first, then extract type
const STATUS = {
ACTIVE: "active",
INACTIVE: "inactive",
PENDING: "pending",
} as const;
type Status = (typeof STATUS)[keyof typeof STATUS];
// ❌ NEVER: Direct union types
type Status = "active" | "inactive" | "pending";
理由: 唯一の信頼できる情報源、実行時の値、オートコンプリート、リファクタリングの容易さ。
フラットなインターフェース(必須)
// ✅ ALWAYS: One level depth, nested objects → dedicated interface
interface UserAddress {
street: string;
city: string;
}
interface User {
id: string;
name: string;
address: UserAddress; // Reference, not inline
}
interface Admin extends User {
permissions: string[];
}
// ❌ NEVER: Inline nested objects
interface User {
address: { street: string; city: string }; // NO!
}
any は絶対に使用しない
// ✅ Use unknown for truly unknown types
function parse(input: unknown): User {
if (isUser(input)) return input;
throw new Error("Invalid input");
}
// ✅ Use generics for flexible types
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
// ❌ NEVER
function parse(input: any): any { }
ユーティリティ型
Pick<User, "id" | "name"> // Select fields
Omit<User, "id"> // Exclude fields
Partial<User> // All optional
Required<User> // All required
Readonly<User> // All readonly
Record<string, User> // Object type
Extract<Union, "a" | "b"> // Extract from union
Exclude<Union, "a"> // Exclude from union
NonNullable<T | null> // Remove null/undefined
ReturnType<typeof fn> // Function return type
Parameters<typeof fn> // Function params tuple
型ガード
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value
);
}
型のインポート
import type { User } from "./types";
import { createUser, type Config } from "./utils";
キーワード
typescript, ts, types, interfaces, generics, strict mode, utility types
コメント
Markdown 対応