Token导航 LogoToken导航

Agent Skill · 开发

typescript-advanced-patterns(TypeScript 高级模式)

typescript-advanced-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

typescript-advanced-patterns 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 12,214。

总安装 1,392周安装 58GitHub Stars 98下载 464核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:typescript-advanced-patterns(TypeScript 高级模式)
来源仓库:https://github.com/erichowens/some_claude_skills
仓库路径:skills/typescript-advanced-patterns
安装命令:
npx skills add https://github.com/erichowens/some_claude_skills --skill typescript-advanced-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/erichowens/some_claude_skills --skill typescript-advanced-patterns

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

利用编译期类型约束消除运行时 bug 的高级 TypeScript 模式库。涵盖品牌类型、名义类型、模板字面量类型和条件类型等进阶用法。提供满足运算符使用、const 断言和 Zod 推断等实用技巧指导。适用于需要强类型保证的金融、医疗等高风险系统开发场景。使用时需权衡类型复杂度与维护成本,避免过度设计简单业务逻辑。

来源仓库内路径:skills/typescript-advanced-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/erichowens/some_claude_skills --skill typescri…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

typescript-advanced-patterns 怎么安装?

在终端执行 npx skills add https://github.com/erichowens/some_claude_skills --skill typescript-advance…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

typescript-advanced-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

typescript-advanced-patterns 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

typescript-advanced-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

typescript-advanced-patterns 用的人多吗?

公开数据是累计安装 1,392 次,近一周安装 58 次,下载 464 次,GitHub 98 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

typescript-advanced-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
typescript-advanced-patterns

TypeScript 高级模式 · 本页

1,39298需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

TypeScript Advanced Patterns

Advanced type system patterns that eliminate runtime bugs by encoding constraints at compile time.

When to Use

Activate on: "branded types", "nominal typing", "discriminated union", "template literal types", "conditional types", "infer keyword", "satisfies operator", "const assertion", "Zod inference", "exhaustive switch", "type-safe event emitter", "mapped types", "utility types", "generic constraints", "type narrowing", "as const"

NOT for: Basic TypeScript syntax | React component prop types | General JavaScript patterns

Decision Tree: Which Advanced Pattern for Your Problem?

flowchart TD
    P[What is your problem?] --> P1[I'm mixing up\nvalues of the same type\ne.g. UserId vs OrderId]
    P[What is your problem?] --> P2[I have a value that\ncan be one of N shapes]
    P[What is your problem?] --> P3[I need type-safe\nevent emitting]
    P[What is your problem?] --> P4[I'm parsing external\ndata and want types]
    P[What is your problem?] --> P5[I want types that\ndepend on other types]
    P[What is your problem?] --> P6[My switch/if is\nnot exhaustive]

    P1 --> S1[Branded Types\nfor nominal typing]
    P2 --> S2[Discriminated Unions\nwith type narrowing]
    P3 --> S3[Type-Safe Event Emitter\nwith mapped types]
    P4 --> S4[Zod schema + z.infer\nfor runtime + compile time]
    P5 --> S5[Conditional Types\nwith infer keyword]
    P6 --> S6[Exhaustive checking\nwith never type]

Core Patterns

1. Branded Types (Nominal Typing)

TypeScript's structural type system means UserId and string are assignable to each other. Branded types add a phantom brand that makes them incompatible.

// Without branding: these compile without error
function chargeUser(userId: string, amount: number) { /* ... */ }
const orderId = getOrderId();
chargeUser(orderId, 100); // Wrong! orderId passed as userId — TypeScript allows it

// With branding: compile-time protection
type Brand<T, B extends string> = T & { readonly __brand: B };

type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
type EmailAddress = Brand<string, 'EmailAddress'>;
type Cents = Brand<number, 'Cents'>;  // Never pass raw numbers as money

// Constructor functions (only way to create branded values)
const UserId = (id: string): UserId => id as UserId;
const OrderId = (id: string): OrderId => id as OrderId;
const Cents = (n: number): Cents => {
  if (!Number.isInteger(n) || n < 0) throw new Error(`Invalid cents: ${n}`);
  return n as Cents;
};

// Usage: type error if you mix them up
function chargeUser(userId: UserId, amount: Cents) { /* ... */ }

const uid = UserId('user_123');
const oid = OrderId('order_456');

chargeUser(uid, Cents(1000));  // OK
chargeUser(oid, Cents(1000));  // Error: Argument of type 'OrderId' is not assignable to 'UserId'
chargeUser(uid, 1000);         // Error: Argument of type 'number' is not assignable to 'Cents'

See references/branded-types.md for Zod integration and database model patterns.

2. Discriminated Unions with Type Narrowing

The kind (or type, tag) field is the discriminant. TypeScript narrows the union when you check it.

type ApiResult<T> =
  | { status: 'success'; data: T }
  | { status: 'error'; code: number; message: string }
  | { status: 'loading' };

function handleResult<T>(result: ApiResult<T>): T | null {
  switch (result.status) {
    case 'success': return result.data;        // TypeScript knows data exists here
    case 'error':   console.error(result.code, result.message); return null;
    case 'loading': return null;
  }
}

With exhaustive checking — if a new variant is added and the switch is not updated, it's a compile error:

function assertNever(x: never): never {
  throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
}

function handleResult<T>(result: ApiResult<T>): T | null {
  switch (result.status) {
    case 'success': return result.data;
    case 'error':   return null;
    // If 'loading' is not handled, TypeScript errors:
    // Argument of type '{ status: "loading" }' is not assignable to 'never'
    default: return assertNever(result);
  }
}

3. Template Literal Types

Combine string literals at type level to create precise types for string-based APIs:

// Route path types — prevents typos in route definitions
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type ApiVersion = 'v1' | 'v2';
type Resource = 'users' | 'orders' | 'products';

type ApiEndpoint = `/${ApiVersion}/${Resource}`;
// Type: "/v1/users" | "/v1/orders" | "/v1/products" | "/v2/users" | ...

// CSS-in-JS property types
type CSSProperty = 'margin' | 'padding' | 'border';
type Side = 'top' | 'right' | 'bottom' | 'left';
type CSSPropertyWithSide = `${CSSProperty}-${Side}`;
// Type: "margin-top" | "margin-right" | ... | "border-left"

// Event name types
type DOMEventMap = {
  click: MouseEvent;
  keydown: KeyboardEvent;
  input: InputEvent;
};
type EventName = `on${Capitalize<keyof DOMEventMap>}`;
// Type: "onClick" | "onKeydown" | "onInput"

4. Conditional Types with infer

infer extracts a type from within another type during conditional type evaluation.

// Extract the return type of an async function
type Awaited<T> = T extends Promise<infer U> ? U : T;

type UserFetch = () => Promise<{ id: string; name: string }>;
type User = Awaited<ReturnType<UserFetch>>;
// Type: { id: string; name: string }

// Extract the element type of an array
type ElementOf<T> = T extends (infer U)[] ? U : never;
type Names = ElementOf<string[]>;  // string
type Events = ElementOf<Array<{ id: number; type: string }>>;  // { id: number; type: string }

// Extract handler parameters from an event map
type HandlerParams<T extends (...args: any) => any> =
  T extends (...args: infer P) => any ? P : never;

// Deeply unwrap Promises
type DeepAwaited<T> = T extends Promise<infer U> ? DeepAwaited<U> : T;
type Result = DeepAwaited<Promise<Promise<string>>>;  // string

5. The satisfies Operator (TypeScript 4.9+)

satisfies validates a value against a type without widening it. You get both type checking AND the most specific inferred type.

type Color = string | [number, number, number];

// Problem with 'as': loses specific type info
const colors = {
  red: [255, 0, 0] as Color,    // type is Color, not [255, 0, 0]
  blue: [0, 0, 255] as Color,
} as Record<string, Color>;

// Problem with annotation: same widening
const colors2: Record<string, Color> = {
  red: [255, 0, 0],   // type is Color
};

// satisfies: validates AND preserves specific type
const colors3 = {
  red: [255, 0, 0],
  blue: [0, 0, 255],
} satisfies Record<string, Color>;

colors3.red.map(x => x * 2);   // OK: TypeScript knows it's [number, number, number]
colors3.blue[0];                // OK: indexed access works

// Great for config objects
const config = {
  port: 3000,
  host: 'localhost',
  debug: false,
} satisfies {
  port: number;
  host: string;
  debug: boolean;
  timeout?: number;  // optional fields allowed to be absent
};

config.port.toFixed(0);   // OK: port is still `number`, not widened to `number | string`

6. Zod Schema Inference

Zod validates at runtime and provides TypeScript types for free. Never write a type + validator separately.

import { z } from 'zod';

// Define schema once
const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  role: z.enum(['admin', 'user', 'moderator']),
  createdAt: z.coerce.date(),
  metadata: z.record(z.string(), z.unknown()).optional(),
});

// Extract type — no duplicate type definition
type User = z.infer<typeof UserSchema>;
// Type: { id: string; email: string; role: "admin" | "user" | "moderator"; createdAt: Date; metadata?: Record<string, unknown> }

// Parse with validation
function parseUser(raw: unknown): User {
  return UserSchema.parse(raw);  // throws ZodError with structured errors on failure
}

// Safe parse (returns Result type)
const result = UserSchema.safeParse(rawData);
if (result.success) {
  result.data.role;  // narrowed to User
} else {
  result.error.issues;  // structured validation errors
}

// Derive related schemas
const CreateUserInput = UserSchema.omit({ id: true, createdAt: true });
type CreateUserInput = z.infer<typeof CreateUserInput>;

const UpdateUserInput = UserSchema.partial().required({ id: true });

See references/type-safe-patterns.md for type-safe event emitters, builder pattern, and exhaustive checking utilities.

Reference Files

FileContents
references/branded-types.mdBranded primitives for IDs/currencies/emails, Zod integration, database patterns
references/type-safe-patterns.mdExhaustive switch, builder pattern, type-safe event emitters, mapped type utilities

Anti-Patterns (Shibboleths)

Anti-Pattern 1: any as an Escape Hatch Instead of Proper Generics

Novice thinking: "This is too complex to type, I'll just use any and come back to it later."

Why wrong: any disables all type checking for that value AND spreads to anything it touches. any is contagious — once a value is any, functions that receive it infer their return type as any, creating a type hole that grows over time. The "come back to it" never happens.

Detection: as any in a codebase almost always signals a type design problem, not a TypeScript limitation.

Fix — Use generics with constraints:

// Bad: uses any to avoid figuring out the right type
function processItems(items: any[]): any[] {
  return items.filter(item => item.active);
}

// Good: generic with constraint
function processItems<T extends { active: boolean }>(items: T[]): T[] {
  return items.filter(item => item.active);
}

// Better: if you just need "has a property", use unknown and narrow
function getProperty(obj: unknown, key: string): unknown {
  if (typeof obj === 'object' && obj !== null && key in obj) {
    return (obj as Record<string, unknown>)[key];
  }
  return undefined;
}

Fix — Use unknown instead of any for truly unknown data:

// Bad: any propagates
function parseData(raw: any) {
  return raw.user.id;  // No error, will crash if shape is wrong
}

// Good: unknown forces you to narrow
function parseData(raw: unknown) {
  if (
    typeof raw === 'object' &&
    raw !== null &&
    'user' in raw &&
    typeof (raw as any).user === 'object'
  ) {
    // Now you can access safely
  }
  // Better: use Zod
  return UserSchema.parse(raw);
}

Shibboleth: any means "I don't know and I don't want TypeScript to check." unknown means "I don't know, but I will check before using." Prefer unknown at API boundaries, never any.


Anti-Pattern 2: Over-Engineering Types When Simpler Types Suffice

Novice thinking (advanced TypeScript user): "I can encode this entire business rule in the type system using conditional types and template literals!"

Why wrong: Type complexity has a real cost. Conditional types with multiple infer levels produce error messages that take three minutes to parse. Junior engineers cannot maintain them. IDE autocomplete slows to a crawl. Types that take 200ms to compute create an unpleasant editing experience across the whole file.

The calibration question: Does the type complexity prevent a category of bug that would actually happen? If yes, it's worth it. If you're just proving you can do it, simplify.

Examples of appropriate vs. over-engineered:

// APPROPRIATE: Branded types prevent real mixing bugs
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;

// APPROPRIATE: Discriminated union encodes real state machine
type AuthState =
  | { status: 'logged_out' }
  | { status: 'logging_in' }
  | { status: 'logged_in'; user: User; token: string };

// OVER-ENGINEERED: Encoding HTTP method semantics in types
// Does this actually prevent bugs? Probably not.
type HttpMethodHasBody<M extends HttpMethod> =
  M extends 'POST' | 'PUT' | 'PATCH' ? true : false;

type RequestWithBody<M extends HttpMethod> =
  HttpMethodHasBody<M> extends true
    ? { method: M; body: unknown }
    : { method: M; body?: never };

// OVER-ENGINEERED: Recursive type for deeply nested access
// Causes slow compilation and unreadable errors
type DeepGet<T, Path extends string> =
  Path extends `${infer Head}.${infer Tail}`
    ? Head extends keyof T
      ? DeepGet<T[Head], Tail>
      : never
    : Path extends keyof T
      ? T[Path]
      : never;
// Use lodash.get + unknown return type instead

Decision heuristic: If you cannot explain the type in one sentence, it needs a comment. If you need more than two sentences, reconsider whether a simpler approach (runtime validation, a helper function) is more maintainable.

Shibboleth: Expert TypeScript engineers know when NOT to use advanced types. The goal is fewer bugs and better DX, not demonstrating mastery of the type system. Simple union types beat complex conditional types when both achieve the same bug prevention.

Quality Checklist

[ ] No bare `any` types — unknown or generics used instead
[ ] Primitive values that must not be mixed are branded (IDs, money, emails)
[ ] Sum types use discriminated unions, not boolean flags
[ ] External data parsed through Zod schemas (never typed as a known type without validation)
[ ] Switch statements over union types use exhaustive checking
[ ] Conditional types include a comment explaining what they compute
[ ] No type aliases that just rename primitives without branding
[ ] Generic constraints are as specific as needed, no more
[ ] satisfies used for config objects instead of widening assertions
[ ] Type-level tests (expect-type) for complex utility types

Output Artifacts

  1. Domain type module — Branded types for all primitive domain values (IDs, money, emails)
  2. Zod schemas — Schema definitions with exported z.infer types
  3. Discriminated union definitions — State machines, API results, domain events
  4. Type-safe event emitter — Generic EventEmitter with typed events map
  5. Utility types — Reusable conditional type utilities for the project

平台分布

Codex

39.29%
按下载量换算182

Claude

28.4%
按下载量换算132

Cursor

17.92%
按下载量换算83

Gemini CLI

9.65%
按下载量换算45

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills