Agent skill

Typescript Best Practices

by bretzel-app in bretzel-app/crumbs

Provides TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive handling, and runtime validation.

MITAuto-check passedFrontend & Design

Install Typescript Best Practices

skills CLI
$ npx skills add bretzel-app/crumbs --skill typescript-best-practices -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install bretzel-app/crumbs typescript-best-practices --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/bretzel-app/crumbs.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/typescript-best-practices .claude/skills/typescript-best-practices && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
typescript-best-practices
GitHub stars
127
Used in
1 other repo
Token cost
~2.2k tokens
SKILL.md length
540 words
Files
1
Skills in repo
2
Repo updated
First seen
Licence
MIT

At a glance

Provides TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive handling, and runtime validation.

  • Works in 4 steps: Define the data model - types,… → Define function signatures -… → Implement to satisfy types - let the… → …
  • Writing TypeScript/JavaScript files
  • SKILL.md covers Pair with React Best Practices, Type-First Development, Module Structure and Functional Patterns, plus 5 more sections
  • Needs API_KEY

What it does

Typescript Best Practices is an agent skill from bretzel-app/crumbs. Provides TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive handling, and runtime validation. Must use when reading or writing TypeScript/JavaScript files.

Its SKILL.md is about 2.2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Frontend & Design, covering React components. It works with TypeScript, JavaScript, SvelteKit and React. The repository describes itself as: Crumbs by Bretzel - a self-hosted, privacy-first Google Keep alternative. Capture your thoughts, ideas and notes. Built with SvelteKit. The licence is MIT.

When your agent uses it

  • Writing TypeScript/JavaScript files
  • Tasks that involve React components

Example prompts

  • “Use the typescript-best-practices skill to provide TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive…”
  • “/typescript-best-practices”

Requirements

  • A credential in API_KEY

Workflow steps

4 steps, taken from the first numbered list in SKILL.md.

  1. Define the data model - types, interfaces, and schemas first
  2. Define function signatures - input/output types before logic
  3. Implement to satisfy types - let the compiler guide completeness
  4. Validate at boundaries - runtime checks where data enters the system

What it can do on your machine

Read from SKILL.md and the folder at commit 31732e8. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Typescript Best Practices loads about 2.2k tokens when it runs. Until then it costs about 57 tokens; SKILL.md has 540 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~57
When it runs · the whole SKILL.md, loaded when a task matches
~2.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from bretzel-app/crumbs at commit 31732e8, republished under its MIT licence (© bretzel-app). 540 words, ~2,176 tokens.

Download SKILL.mdSave it as .claude/skills/typescript-best-practices/SKILL.md (or your agent's skills folder).
name
typescript-best-practices
description
Provides TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive handling, and runtime validation. Must use when reading or writing TypeScript/JavaScript files.

TypeScript Best Practices

Pair with React Best Practices

When working with React components (.tsx, .jsx files or @react imports), always load react-best-practices alongside this skill. This skill covers TypeScript fundamentals; React-specific patterns (effects, hooks, refs, component design) are in the dedicated React skill.

Type-First Development

Types define the contract before implementation. Follow this workflow:

  1. Define the data model - types, interfaces, and schemas first
  2. Define function signatures - input/output types before logic
  3. Implement to satisfy types - let the compiler guide completeness
  4. Validate at boundaries - runtime checks where data enters the system
Make Illegal States Unrepresentable

Use the type system to prevent invalid states at compile time.

Discriminated unions for mutually exclusive states:

ts
// Good: only valid combinations possible
type RequestState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: Error };

// Bad: allows invalid combinations like { loading: true, error: Error }
type RequestState<T> = {
  loading: boolean;
  data?: T;
  error?: Error;
};

Branded types for domain primitives:

ts
type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };

// Compiler prevents passing OrderId where UserId expected
function getUser(id: UserId): Promise<User> { /* ... */ }

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

Const assertions for literal unions:

ts
const ROLES = ['admin', 'user', 'guest'] as const;
type Role = typeof ROLES[number]; // 'admin' | 'user' | 'guest'

// Array and type stay in sync automatically
function isValidRole(role: string): role is Role {
  return ROLES.includes(role as Role);
}

Required vs optional fields - be explicit:

ts
// Creation: some fields required
type CreateUser = {
  email: string;
  name: string;
};

// Update: all fields optional
type UpdateUser = Partial<CreateUser>;

// Database row: all fields present
type User = CreateUser & {
  id: UserId;
  createdAt: Date;
};

Module Structure

Prefer smaller, focused files: one component, hook, or utility per file. Split when a file handles multiple concerns or exceeds ~200 lines. Colocate tests with implementation (foo.test.ts alongside foo.ts). Group related files by feature rather than by type.

Functional Patterns

  • Prefer const over let; use readonly and Readonly<T> for immutable data.
  • Use array.map/filter/reduce over for loops; chain transformations in pipelines.
  • Write pure functions for business logic; isolate side effects in dedicated modules.
  • Avoid mutating function parameters; return new objects/arrays instead.

Instructions

  • Enable strict mode; model data with interfaces and types. Strong typing catches bugs at compile time.
  • Every code path returns a value or throws; use exhaustive switch with never checks in default. Unhandled cases become compile errors.
  • Propagate errors with context; catching requires re-throwing or returning a meaningful result. Hidden failures delay debugging.
  • Handle edge cases explicitly: empty arrays, null/undefined inputs, boundary values. Defensive checks prevent runtime surprises.
  • Use await for async calls; wrap external calls with contextual error messages. Unhandled rejections crash Node processes.
  • Add or update focused tests when changing logic; test behavior, not implementation details.

Examples

Explicit failure for unimplemented logic:

ts
export function buildWidget(widgetType: string): never {
  throw new Error(`buildWidget not implemented for type: ${widgetType}`);
}

Exhaustive switch with never check:

ts
type Status = "active" | "inactive";

export function processStatus(status: Status): string {
  switch (status) {
    case "active":
      return "processing";
    case "inactive":
      return "skipped";
    default: {
      const _exhaustive: never = status;
      throw new Error(`unhandled status: ${_exhaustive}`);
    }
  }
}

Wrap external calls with context:

ts
export async function fetchWidget(id: string): Promise<Widget> {
  const response = await fetch(`/api/widgets/${id}`);
  if (!response.ok) {
    throw new Error(`fetch widget ${id} failed: ${response.status}`);
  }
  return response.json();
}

Debug logging with namespaced logger:

ts
import debug from "debug";

const log = debug("myapp:widgets");

export function createWidget(name: string): Widget {
  log("creating widget: %s", name);
  const widget = { id: crypto.randomUUID(), name };
  log("created widget: %s", widget.id);
  return widget;
}
Show full SKILL.md (208 more words)Show less

Runtime Validation with Zod

  • Define schemas as single source of truth; infer TypeScript types with z.infer<>. Avoid duplicating types and schemas.
  • Use safeParse for user input where failure is expected; use parse at trust boundaries where invalid data is a bug.
  • Compose schemas with .extend(), .pick(), .omit(), .merge() for DRY definitions.
  • Add .transform() for data normalization at parse time (trim strings, parse dates).
  • Include descriptive error messages; use .refine() for custom validation logic.
Examples

Schema as source of truth with type inference:

ts
import { z } from "zod";

const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  name: z.string().min(1),
  createdAt: z.string().transform((s) => new Date(s)),
});

type User = z.infer<typeof UserSchema>;

Return parse results to callers (never swallow errors):

ts
import { z, SafeParseReturnType } from "zod";

export function parseUserInput(raw: unknown): SafeParseReturnType<unknown, User> {
  return UserSchema.safeParse(raw);
}

// Caller handles both success and error:
const result = parseUserInput(formData);
if (!result.success) {
  setErrors(result.error.flatten().fieldErrors);
  return;
}
await submitUser(result.data);

Strict parsing at trust boundaries:

ts
export async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new Error(`fetch user ${id} failed: ${response.status}`);
  }
  const data = await response.json();
  return UserSchema.parse(data); // throws if API contract violated
}

Schema composition:

ts
const CreateUserSchema = UserSchema.omit({ id: true, createdAt: true });
const UpdateUserSchema = CreateUserSchema.partial();
const UserWithPostsSchema = UserSchema.extend({
  posts: z.array(PostSchema),
});

Configuration

  • Load config from environment variables at startup; validate with Zod before use. Invalid config should crash immediately.
  • Define a typed config object as single source of truth; avoid accessing process.env throughout the codebase.
  • Use sensible defaults for development; require explicit values for production secrets.
Examples

Typed config with Zod validation:

ts
import { z } from "zod";

const ConfigSchema = z.object({
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  API_KEY: z.string().min(1),
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
});

export const config = ConfigSchema.parse(process.env);

Access config values (not process.env directly):

ts
import { config } from "./config";

const server = app.listen(config.PORT);
const db = connect(config.DATABASE_URL);

Optional: type-fest

For advanced type utilities beyond TypeScript builtins, consider type-fest:

  • Opaque<T, Token> - cleaner branded types than manual & { __brand } pattern
  • PartialDeep<T> - recursive partial for nested objects
  • ReadonlyDeep<T> - recursive readonly for immutable data
  • LiteralUnion<Literals, Fallback> - literals with autocomplete + string fallback
  • SetRequired<T, K> / SetOptional<T, K> - targeted field modifications
  • Simplify<T> - flatten complex intersection types in IDE tooltips
ts
import type { Opaque, PartialDeep, SetRequired } from 'type-fest';

// Branded type (cleaner than manual approach)
type UserId = Opaque<string, 'UserId'>;

// Deep partial for patch operations
type UserPatch = PartialDeep<User>;

// Make specific fields required
type UserWithEmail = SetRequired<Partial<User>, 'email'>;

© bretzel-app, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .agents/skills/typescript-best-practices of bretzel-app/crumbs.

Open the folder on GitHubat commit 31732e8

Used in 1 other repository

We found 1 copy of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in bretzel-app/crumbs, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Typescript Best Practices next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Typescript Best Practices compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Typescript Best Practices this skillbretzel-app/crumbs1271 repos~2.2kAutomated safety check: PassMIT
Connect Component To Figmadequelabs/cauldron129—~2kAutomated safety check: PassMPL-2.0
Fork And GoSimplePDF/simplepdf-embed407—~7.9kAutomated safety check: NotesMIT
Javascript Practiceseser/stack128—~599Automated safety check: PassCustom licence
Typescript Rulessoftspark/ai-toolkit179—~2.7kAutomated safety check: NotesApache-2.0
Web Artifacts Builderanthropics/skills180k41 repos~769Automated safety check: PassApache-2.0

Similar skills

  • Connect Component To Figma

    dequelabs/cauldron

    Add a Figma Code Connect (.figma.tsx) file for a Cauldron React component.

    129 GitHub stars~2k tokensUpdated today
    Frontend & DesignAuto-check passed
  • Fork And Go

    SimplePDF/simplepdf-embed

    Guided walkthrough for forking and deploying your own SimplePDF Copilot: hosting choice, Pro-account confirmation, AI-provider wiring, demo customization, deploy, and the SimplePDF whitelist step.

    407 GitHub stars~7.9k tokensUpdated 7 days ago
    Frontend & DesignAuto-check: notes
  • TS and JS conventions for eserstack packages: namespace imports, mod.ts entries, cross-runtime APIs, explicit checks, async, tests and laroux React components.

    128 GitHub stars~599 tokensUpdated 4 days ago
    Frontend & DesignAuto-check passed
  • Typescript Rules

    softspark/ai-toolkit

    TypeScript/JavaScript coding rules: style, patterns, security, testing.

    179 GitHub stars~2.7k tokensUpdated yesterday
    Testing & QAAuto-check: notes
  • Web Artifacts Builder

    anthropics/skills

    Official

    Builds multi-component claude.ai HTML artifacts as a small React, TypeScript and Tailwind project, then bundles it into one shareable HTML file.

    180k GitHub starsUsed in 41 repos~769 tokens
    Frontend & DesignAuto-check passed
  • Use when implementing or refactoring React/TypeScript components and the task requires decisions about component ownership, feature boundaries, state, data…

    158k GitHub stars~626 tokensUpdated today
    Frontend & DesignAuto-check passed

More from bretzel-app/crumbs

  • Drizzle Migrations

    bretzel-app/crumbs

    Drizzle ORM schema management and SQLite migrations — adding tables, modifying columns, creating indexes, generating and running migrations, Drizzle query patterns.

    127 GitHub starsUsed in 1 repo~2.6k tokens
    Auto-check passed

Questions about Typescript Best Practices

What does Typescript Best Practices do?

Provides TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive handling, and runtime validation. Typescript Best Practices is an agent skill from bretzel-app/crumbs. Provides TypeScript patterns for type-first development, making illegal states unrepresentable, exhaustive handling, and runtime validation.

When should I use Typescript Best Practices?

Typescript Best Practices fits situations like: writing TypeScript/JavaScript files; tasks that involve React components.

How do I install Typescript Best Practices in Claude Code?

Run `npx skills add bretzel-app/crumbs --skill typescript-best-practices -a claude-code`. Or copy the skill folder (.agents/skills/typescript-best-practices in bretzel-app/crumbs) into .claude/skills/typescript-best-practices in your project. Claude Code loads it when a task matches its description.

How do I install Typescript Best Practices in Codex?

Run `npx skills add bretzel-app/crumbs --skill typescript-best-practices -a codex`. Or copy the skill folder (.agents/skills/typescript-best-practices in bretzel-app/crumbs) into .agents/skills/typescript-best-practices in your project. Codex loads it when a task matches its description.

Can I use Typescript Best Practices in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add bretzel-app/crumbs --skill typescript-best-practices -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/typescript-best-practices, .gemini/skills/typescript-best-practices, .github/skills/typescript-best-practices and .opencode/skills/typescript-best-practices in your project.

What does Typescript Best Practices need to run?

Going by SKILL.md and its folder, Typescript Best Practices needs credentials named API_KEY. Our summary lists: A credential in API_KEY.

Does Typescript Best Practices access the network?

SKILL.md names 1 domain. As links in the text: github.com. This is read from the text; nothing was executed.

Is Typescript Best Practices safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Typescript Best Practices use?

Typescript Best Practices is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Typescript Best Practices use?

About 2.2k tokens (SKILL.md is roughly 8.7k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Typescript Best Practices?

Skills that share tags, products or a category with Typescript Best Practices: Connect Component To Figma (dequelabs/cauldron, 129 stars), Fork And Go (SimplePDF/simplepdf-embed, 407 stars), Javascript Practices (eser/stack, 128 stars) and Typescript Rules (softspark/ai-toolkit, 179 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Typescript Best Practices?

bretzel-app (a GitHub organization) maintains it in bretzel-app/crumbs, which has 127 GitHub stars. The repository holds 2 skills in this directory. The repository was last updated on October 6, 2026.

Source: bretzel-app/crumbs on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.