Typescript Patterns logo

Typescript Patterns

Community
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.

Overview

Publisherkazdenc
Repositorybuilder-skills
Skill nametypescript-patterns
Stars
46
Forks
5
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by kazdenc on GitHub. Read the source before you install it.

Installation

Install the Typescript Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/kazdenc/builder-skills/tree/main/.claude/skills/dev/frameworks/typescript-patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Typescript Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Typescript Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Typescript Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

Frequently asked questions

What does the Typescript Patterns AI skill do?

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.

Why use Typescript Patterns on TypingMind?

Because you install it once and use it with any model. Typescript Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Typescript Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/kazdenc/builder-skills/tree/main/.claude/skills/dev/frameworks/typescript-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Typescript Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Typescript Patterns?

As many as you like. As long as a model supports skills, you can use Typescript Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Typescript Patterns AI skill free?

Yes. It is published on GitHub by kazdenc under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇