Index of every page on this site: llms.txt
All skills
grahamcrackers avatar

/typescript-advanced-patterns

@ca83de4
Run it yourself

Advanced TypeScript type-level patterns including generics, branded types, discriminated unions, template literals, conditional types, and type-safe builders. Use when working on complex TypeScript type design, creating type-safe APIs, building libraries, or when the user asks about advanced type patterns.

Use this Skill: https://skilld.dev/gh/grahamcrackers/skills/typescript-advanced-patterns

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

SKILL.md

≈84 tokens for metadata: the name and description. ≈1.1k when used: this file.

Description uses 4.2% of example budget

Before choosing a Skill, your Agent reads its name and description. All available Skills share that space.

  • A shorter description leaves more room for other Skills. This entry exceeds our 1% size suggestion.

In our Claude Code example, all Skill names and descriptions share 8,000 characters. This Skill uses ≈338 characters, or 4.2%.

The 1% threshold is a size suggestion. Longer descriptions can still fit.

Your model, settings, and other Skills decide how much text your Agent can read.

Example settings and source

The example uses a 200k-token context and default Claude Code settings. The count includes the name, description, separators, and when_to_use when present. Codex also counts local file paths.

Skit's source and limits: Codex 0.160.1, Claude Code 2.1.292.

TypeScript Advanced Patterns

Discriminated Unions

Model state machines and mutually exclusive variants with a shared literal discriminant:

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

function handle(result: Result<User>) {
    if (result.success) {
        console.log(result.data.name); // narrowed to { data: User }
    } else {
        console.error(result.error); // narrowed to { error: Error }
    }
}

Prefer discriminated unions over optional fields when states are mutually exclusive.

Branded / Nominal Types

Prevent accidental value interchange between structurally identical types:

type Brand<T, B extends string> = T & { readonly __brand: B };

type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;

function getUser(id: UserId): User {
    /* ... */
}

const userId = "abc" as UserId;
const orderId = "abc" as OrderId;
getUser(orderId); // Type error

Use branded types for IDs, validated strings, currency amounts, and other domain primitives.

Template Literal Types

Build type-safe string patterns:

type EventName = `on${Capitalize<string>}`;
type CSSUnit = `${number}${"px" | "rem" | "em" | "%"}`;
type Route = `/${string}`;

Combine with mapped types for type-safe event handlers, CSS-in-JS, or API routes.

Conditional Types

Derive types based on conditions:

type IsArray<T> = T extends readonly unknown[] ? true : false;

type Unwrap<T> = T extends Promise<infer U> ? Unwrap<U> : T extends readonly (infer U)[] ? U : T;

Use infer to extract inner types. Keep conditional types shallow — deeply nested conditionals become unreadable.

Mapped Types with Key Remapping

Transform object types:

type Getters<T> = {
    [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

Type-Safe Builder Pattern

Chain methods while accumulating type information:

class QueryBuilder<T extends Record<string, unknown>> {
    select<K extends keyof T>(...keys: K[]): QueryBuilder<Pick<T, K>> {
        return this as unknown as QueryBuilder<Pick<T, K>>;
    }

    where<K extends keyof T>(key: K, value: T[K]): QueryBuilder<T> {
        return this;
    }
}

Exhaustive Pattern Matching

Ensure all union variants are handled at compile time:

function assertNever(value: never): never {
    throw new Error(`Unhandled value: ${value}`);
}

function handleStatus(status: Status) {
    switch (status) {
        case "active":
            return "Active";
        case "inactive":
            return "Inactive";
        default:
            return assertNever(status); // compile error if a variant is missed
    }
}

Function Overloads

Provide precise signatures for functions with varying input/output types:

function parse(input: string): Document;
function parse(input: Buffer): Document;
function parse(input: string | Buffer): Document {
    // implementation
}

Prefer discriminated union parameters or generics over overloads when possible — overloads add complexity.

const Type Parameters

Preserve literal types through generic functions (TypeScript 5.0+):

function createRoutes<const T extends readonly string[]>(routes: T): T {
    return routes;
}

const routes = createRoutes(["/home", "/about"]); // readonly ["/home", "/about"]

Type-Safe Record Factories

Constrain records to specific key sets:

function createLookup<K extends string, V>(keys: readonly K[], valueFn: (key: K) => V): Record<K, V> {
    return Object.fromEntries(keys.map((k) => [k, valueFn(k)])) as Record<K, V>;
}

Module Augmentation

Extend third-party types without forking:

declare module "express" {
    interface Request {
        user?: AuthenticatedUser;
    }
}

Keep augmentations in a dedicated *.d.ts file and reference it in tsconfig.json.

Guidelines

  • Favor readability over cleverness — if a type requires a paragraph to explain, simplify it.
  • Test complex types with Expect / Equal utilities (e.g., from type-testing or expect-type).
  • Document non-obvious type-level logic with a brief comment above the type.
  • Avoid recursive types deeper than 3-4 levels — they can crash the compiler or produce cryptic errors.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts28d4 checks · Risk SAFE
  • Gen Agent Trust Hub28d

    The skill provides advanced TypeScript type-level patterns and guidelines. It contains no executable code, remote dependencies, or security risks.

  • Socket28d

    No alerts

  • Snyk28d

    Risk: LOW · No issues

  • Runlayer9mo

    1 file scanned · No issues

Signed by skilld at ca83de4. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Dormantupdated 9 months ago

README badge

README badge for grahamcrackers/skills/typescript-advanced-patterns