---
name: typescript-advanced-patterns
description: 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.
title: typescript-advanced-patterns
canonical_url: https://skilld.dev/gh/grahamcrackers/skills/typescript-advanced-patterns
last_updated: 2026-10-07T02:20:44.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install grahamcrackers/skills/typescript-advanced-patterns`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/typescript-advanced-patterns`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/grahamcrackers/skills/typescript-advanced-patterns) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/typescript-advanced-patterns`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/typescript-advanced-patterns --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/typescript-advanced-patterns --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# TypeScript Advanced Patterns

## Discriminated Unions

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

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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+):

```typescript
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:

```typescript
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:

```typescript
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.
