Typescript Patternsのロゴ

Typescript Patterns

コミュニティ
kazdenc
typescript-patterns

TypeScript best practices and advanced type design patterns. Use when writing, reviewing, or refactoring TypeScript code. Covers type narrowing, generics, utility types, discriminated unions, error handling, and module patterns. Triggers on TypeScript, type safety, or type design tasks.

概要

公開者kazdenc
リポジトリbuilder-skills
スキル名typescript-patterns
スター
46
フォーク
5
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    kazdencがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルTypescript PatternsをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/kazdenc/builder-skills/tree/main/.claude/skills/dev/frameworks/typescript-patterns
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/kazdenc/builder-skills.git /tmp/builder-skills
mkdir -p .claude/skills
cp -r /tmp/builder-skills/.claude/skills/dev/frameworks/typescript-patterns .claude/skills/typescript-patterns
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでTypescript Patternsを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にTypescript Patternsを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Typescript Patternsは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

TypeScript Patterns

Apply these patterns when writing, reviewing, or refactoring TypeScript code. Prefer type safety over convenience. Catch errors at compile time, not runtime.

Type Design Principles

Default to the narrowest type that accurately represents the data. Widen only when you have a concrete reason.

PrincipleDoDon't
Narrow typesstatus: "active" | "inactive"status: string
Branded types for IDstype UserId = string & { __brand: "UserId" }userId: string (mixable with any string)
Discriminated unions{ kind: "circle"; radius: number } | { kind: "rect"; w: number; h: number }Type assertions to distinguish shapes
Readonly by defaultreadonly items: Item[]Mutable arrays unless mutation is required
Explicit return types on public APIsfunction getUser(id: UserId): Promise<User>Inferred return types on exported functions

Branded Types

Use branded types to prevent accidental mixing of structurally identical values:

typescript
type UserId = string & { readonly __brand: unique symbol };
type OrderId = string & { readonly __brand: unique symbol };

function createUserId(id: string): UserId {
  return id as UserId;
}

function getOrder(orderId: OrderId): Order { /* ... */ }

// Compile error: UserId is not assignable to OrderId
getOrder(createUserId("abc"));

Generics

Use generics when a function or type operates on a value whose type the caller determines. Don't add generics speculatively — add them when you have two or more concrete use cases.

Constraining Generics

Always constrain generics to the narrowest interface they need:

typescript
// Good — constrained to what the function actually uses
function getProperty<T extends Record<string, unknown>, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Bad — unconstrained, anything goes
function getProperty<T>(obj: T, key: string): unknown { /* ... */ }

Common Generic Patterns

Factory pattern — return typed instances:

typescript
function createRepository<T extends { id: string }>(collection: string) {
  return {
    findById(id: string): Promise<T | null> { /* ... */ },
    save(entity: T): Promise<void> { /* ... */ },
    delete(id: string): Promise<void> { /* ... */ },
  };
}

const users = createRepository<User>("users");

Builder pattern — chain methods with progressive type narrowing:

typescript
class QueryBuilder<T> {
  where<K extends keyof T>(field: K, value: T[K]): this { /* ... */ }
  select<K extends keyof T>(...fields: K[]): QueryBuilder<Pick<T, K>> { /* ... */ }
  build(): Query<T> { /* ... */ }
}

Inference helper — let TypeScript infer from arguments:

typescript
function createAction<TInput, TOutput>(config: {
  input: z.ZodSchema<TInput>;
  handler: (input: TInput) => Promise<TOutput>;
}) { /* ... */ }

// TInput and TOutput are inferred from usage
createAction({
  input: z.object({ name: z.string() }),
  handler: async (input) => ({ id: "1", name: input.name }),
});

Utility Types

Use built-in utility types instead of hand-rolling equivalents. Here is when to reach for each:

Utility TypeUse WhenExample
Pick<T, K>You need a subset of propertiesPick<User, "id" | "name"> for a summary view
Omit<T, K>You need everything except certain propertiesOmit<User, "password"> for a public response
Partial<T>All properties become optional (patch/update payloads)Partial<User> for an update endpoint
Required<T>All properties become requiredRequired<Config> after merging with defaults
Record<K, V>You need a typed dictionaryRecord<StatusCode, string> for a lookup table
Extract<T, U>Pull members of a union that match a conditionExtract<Event, { kind: "click" }>
Exclude<T, U>Remove members of a union that match a conditionExclude<Status, "deleted">
NonNullable<T>Strip null and undefined from a typeNonNullable<string | null> after a null check
ReturnType<T>Get the return type of a functionReturnType<typeof fetchUser> to type a variable
Parameters<T>Get the parameter types of a function as a tupleParameters<typeof handler>[0] for the first arg

Combine them for precision: Partial<Pick<User, "name" | "email">> for an optional name-and-email update.

Error Handling

Never throw from library or shared code. Use the Result pattern to make errors part of the type signature.

Result Type

typescript
type Result<T, E = Error> =
  | { ok: true; data: T }
  | { ok: false; error: E };

Apply it consistently:

typescript
type ValidationError = { field: string; message: string };
type AuthError = { code: "UNAUTHORIZED" | "FORBIDDEN"; message: string };

async function createUser(input: CreateUserInput): Promise<Result<User, ValidationError[]>> {
  const errors = validate(input);
  if (errors.length > 0) {
    return { ok: false, error: errors };
  }
  const user = await db.users.create(input);
  return { ok: true, data: user };
}

// Caller handles both paths explicitly
const result = await createUser(input);
if (!result.ok) {
  // result.error is typed as ValidationError[]
  return showErrors(result.error);
}
// result.data is typed as User
console.log(result.data.id);

Typed Error Hierarchies

Use discriminated unions for error types so callers can narrow:

typescript
type AppError =
  | { kind: "validation"; fields: { field: string; message: string }[] }
  | { kind: "not_found"; resource: string; id: string }
  | { kind: "unauthorized"; reason: string }
  | { kind: "internal"; message: string };

When to Throw

Throw only at application boundaries (request handlers, CLI entry points) where you convert Results into HTTP responses or exit codes. Never throw from utility functions, services, or domain logic.

Discriminated Unions

Use discriminated unions for any value that can be in one of several mutually exclusive states. Always use a kind, type, or status field as the discriminant.

State Machines

typescript
type RequestState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: AppError };

API Responses

typescript
type ApiResponse<T> =
  | { ok: true; data: T; meta: { requestId: string } }
  | { ok: false; error: { code: string; message: string; details?: unknown } };

Form States

typescript
type FormState =
  | { step: "input"; values: Partial<FormValues> }
  | { step: "review"; values: FormValues }
  | { step: "submitting"; values: FormValues }
  | { step: "complete"; result: SubmitResult }
  | { step: "error"; values: FormValues; error: string };

Exhaustiveness Checking

Always use a never check in switch statements to catch unhandled variants at compile time:

typescript
function assertNever(value: never): never {
  throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}

function renderState(state: RequestState<User>) {
  switch (state.status) {
    case "idle": return null;
    case "loading": return <Spinner />;
    case "success": return <Profile user={state.data} />;
    case "error": return <ErrorBanner error={state.error} />;
    default: return assertNever(state);
  }
}

Module Patterns

Barrel Exports

Use barrel exports (index.ts) sparingly. They hurt tree-shaking and create circular dependency risks. Prefer direct imports.

ScenarioUse Barrel?Why
Public API of a package/libraryYesProvides a stable import surface
Internal module groupingNoImport directly from the source file
Re-exporting types onlyYesTypes are erased at compile time, no bundle cost

Re-export Types

When a module's types are needed elsewhere but its runtime code is not, re-export types separately:

typescript
// types.ts — pure types, no runtime
export type { User, CreateUserInput, UserRole };

// index.ts — runtime exports
export { createUser, getUser, deleteUser };

Isolate Side Effects

Keep side effects (database connections, env reads, logging init) in dedicated files. Don't mix side-effect code with pure business logic:

typescript
// db.ts — side effect: opens connection
export const db = createConnection(process.env.DATABASE_URL);

// user-service.ts — pure, receives db as dependency
export function createUserService(db: Database) {
  return {
    findById(id: UserId): Promise<User | null> { /* ... */ },
  };
}

Anti-Patterns

Avoid these. When you encounter them in existing code, refactor.

Anti-PatternProblemDo Instead
anyDisables all type checkingUse unknown and narrow, or define the actual type
as type assertionsLies to the compilerUse type guards or discriminated unions to narrow
Non-null assertion !Hides potential null bugsCheck for null explicitly or use optional chaining
enumNon-standard JS, poor tree-shakingUse as const objects or string literal unions
Function typeAccepts anything callableUse specific signatures: (input: T) => R
Object / {}Matches almost everythingUse Record<string, unknown> or a specific interface
namespaceLegacy pattern, poor module compatUse ES modules
Overloads for unionsVerbose, hard to maintainUse a single signature with a discriminated union parameter
@ts-ignoreSilences real errorsFix the type error or use @ts-expect-error with a comment
Index signatures everywhereToo permissiveDefine explicit interfaces for known shapes

よくある質問

AIスキル「Typescript Patterns」では何ができますか?

TypeScript best practices and advanced type design patterns. Use when writing, reviewing, or refactoring TypeScript code. Covers type narrowing, generics, utility types, discriminated unions, error handling, and module patterns. Triggers on TypeScript, type safety, or type design tasks.

TypingMindでTypescript Patternsを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Typescript Patternsはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにTypescript Patternsをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/kazdenc/builder-skills/tree/main/.claude/skills/dev/frameworks/typescript-patternsを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Typescript Patternsを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Typescript Patternsは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもTypescript Patternsを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Typescript Patterns」は無料ですか?

はい。kazdencがGitHubでMITライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇