← 返回 Skills 市场
msruruguay

Typescript Mastery

作者 msruruguay · GitHub ↗ · v1.0.0
cross-platform ✓ 安全检测通过
754
总下载
0
收藏
4
当前安装
1
版本数
在 OpenClaw 中安装
/install typescript-mastery
功能描述
TypeScript advanced patterns — branded types, discriminated unions, template literals, generics, type guards, tsconfig optimization, and migration strategies
使用说明 (SKILL.md)

TypeScript Mastery

Description

Advanced TypeScript patterns for professional-grade applications. Covers branded types for nominal typing, discriminated unions for state machines, template literal types for DSLs, generics with constraints, utility type composition, custom type guards, and performance-tuned tsconfig.json settings. Also includes a practical incremental migration strategy from JavaScript. TypeScript is the #1 language on GitHub in 2026 with 80%+ adoption in new projects.

Usage

Install this skill to get advanced TypeScript patterns including:

  • Branded types to prevent mixing structurally identical types (UserId vs OrderId)
  • Discriminated unions with exhaustiveness checking for state machines
  • Template literal types for type-safe API routes and event names
  • tsconfig.json settings that reduce compilation time by 30-50%
  • Incremental migration strategy from JavaScript to TypeScript

When working on TypeScript projects, this skill provides context for:

  • Designing type-safe APIs using generics and constraints
  • Replacing any with unknown + type narrowing
  • Using as const instead of enums (better tree-shaking)
  • Validating runtime data with Zod instead of type assertions
  • Organizing types to avoid slow inline complex type expressions

Key Patterns

Pattern 1: Branded Types (Nominal Typing)

Prevent accidentally passing the wrong ID or value:

type Brand\x3CT, TBrand> = T & { __brand: TBrand };
type UserId = Brand\x3Cnumber, "UserId">;
type OrderId = Brand\x3Cnumber, "OrderId">;

function createUserId(id: number): UserId { return id as UserId; }
function getUser(id: UserId) { /* ... */ }

const userId = createUserId(123);
const orderId = 456 as OrderId;

getUser(userId);  // OK
getUser(orderId); // Type error -- caught at compile time

Use cases: Database IDs, monetary values (USD, EUR), validated strings (Email, URL).

Pattern 2: Discriminated Unions with Exhaustiveness Checking

type Shape =
  | { type: "circle"; radius: number }
  | { type: "rectangle"; width: number; height: number }
  | { type: "square"; size: number };

function calculateArea(shape: Shape): number {
  switch (shape.type) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "rectangle": return shape.width * shape.height;
    case "square": return shape.size ** 2;
    default:
      const _exhaustive: never = shape;
      throw new Error(`Unhandled shape: ${_exhaustive}`);
  }
}

TypeScript errors when you add a new variant but forget to handle it — perfect for state machines.

Pattern 3: Template Literal Types

type EventNames = "click" | "focus" | "blur";
type EventHandlers = `on${Capitalize\x3CEventNames>}`;
// Result: "onClick" | "onFocus" | "onBlur"

type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
type APIRoute = `/${string}`;
type Endpoint = `${HTTPMethod} ${APIRoute}`;
// Enforces: "GET /users", "POST /users/123", etc.

Pattern 4: Const Assertions (Better Than Enums)

// Use as const instead of enum: no runtime overhead, better tree-shaking
const Status = {
  Active: "ACTIVE",
  Inactive: "INACTIVE",
  Pending: "PENDING"
} as const;

type StatusType = typeof Status[keyof typeof Status];
// "ACTIVE" | "INACTIVE" | "PENDING"

function setStatus(status: StatusType) { /* ... */ }
setStatus(Status.Active);  // OK
setStatus("INVALID");      // Type error

Pattern 5: Custom Type Guards

function isNotNull\x3CT>(value: T | null): value is T {
  return value !== null;
}

const mixed: (string | null)[] = ["a", null, "b", null];
const strings: string[] = mixed.filter(isNotNull);
// Type: string[] -- TypeScript knows nulls are gone

Pattern 6: unknown vs any

// WRONG: 'any' disables type safety -- errors cascade silently
function processInput(data: any) {
  data.nonExistentMethod(); // No error, but crashes at runtime
}

// CORRECT: 'unknown' forces narrowing first
function processInput(data: unknown) {
  if (typeof data === "string") {
    return data.toUpperCase(); // Safe
  }
  throw new Error("Expected string");
}

Pattern 7: Runtime Validation with Zod

// WRONG: type assertion without validation -- silently wrong
const user = JSON.parse(apiResponse) as User;

// CORRECT: validate at the boundary
import { z } from "zod";
const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email()
});
const user = UserSchema.parse(JSON.parse(apiResponse));

Pattern 8: Named Types for Performance

// SLOW: TypeScript re-evaluates complex inline types every use
function processData(input:
  Pick\x3COmit\x3CUser, "password">, "id" | "name"> & { role: string }
) { }

// FAST: TypeScript caches named types (30%+ speedup on large codebases)
type UserBasicInfo = Pick\x3COmit\x3CUser, "password">, "id" | "name">;
type UserWithRole = UserBasicInfo & { role: string };
function processData(input: UserWithRole) { }

tsconfig.json Performance Settings

{
  "compilerOptions": {
    "incremental": true,
    "skipLibCheck": true,
    "isolatedModules": true,
    "strictFunctionTypes": true
  }
}

incremental: 30-50% faster rebuilds. skipLibCheck: 20-40% speed boost. isolatedModules: 32% faster compilation.

Migration Strategy: JavaScript to TypeScript

Phase 1 (Day 1): { "allowJs": true, "checkJs": false, "strict": false }

Phase 2 (Weeks 1-4): Convert bottom-up (no-dependency modules first). Use any temporarily.

Phase 3 (Month 2): { "checkJs": true, "strict": true, "noImplicitAny": true }

Utility Types Reference

type User = { id: number; name: string; password: string };
type PartialUser = Partial\x3CUser>;          // all fields optional
type ReadonlyUser = Readonly\x3CUser>;        // all fields readonly
type PublicUser = Omit\x3CUser, "password">; // remove specific fields
type LoginFields = Pick\x3CUser, "id" | "name">;
type UserMap = Record\x3Cstring, User>;

Tools & References


Published by MidOS — MCP Community Library

安全使用建议
This skill appears to be documentation-only and internally consistent with its purpose. Still consider: (1) the source is unknown and there is no homepage—prefer skills from known authors when possible; (2) review any code it generates before running it in your projects; (3) if the agent suggests installing packages or running commands based on these patterns, inspect those commands and the packages' provenance first. If you want higher assurance, ask the publisher for a homepage or repository link before installing.
功能分析
Type: OpenClaw Skill Name: typescript-mastery Version: 1.0.0 The skill bundle is a purely educational resource providing advanced TypeScript patterns, best practices, and configuration tips. It contains no executable code, malicious instructions, or data exfiltration logic, and its content (SKILL.md) aligns entirely with its stated purpose of teaching TypeScript mastery.
能力评估
Purpose & Capability
Name/description (advanced TypeScript patterns) align with the content: SKILL.md contains TypeScript patterns, tsconfig advice, and migration guidance. The skill requests no binaries, env vars, or config paths—consistent with a documentation/instruction-only skill.
Instruction Scope
The instructions are code examples and prose about type-system patterns and migration strategy. They do not instruct the agent to read system files, access credentials, contact external endpoints, or execute commands outside normal code authoring. No scope creep detected.
Install Mechanism
There is no install spec and no code files. This is lowest-risk (instruction-only) — nothing is written to disk by the skill itself.
Credentials
The skill declares no required environment variables, credentials, or config paths. That is proportionate for a documentation/teaching skill.
Persistence & Privilege
always is false and model invocation is allowed (default). The skill does not request persistent presence or elevated system privileges.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install typescript-mastery
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /typescript-mastery 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release of TypeScript Mastery skill. - Covers advanced TypeScript patterns: branded types, discriminated unions, template literals, generics, and type guards. - Includes practical tsconfig optimization for faster builds and efficient large codebases. - Offers a step-by-step migration strategy from JavaScript to TypeScript. - Features best practices for runtime data validation, utility types, and improved tree-shaking. - Provides concise usage examples and references to essential TypeScript resources.
元数据
Slug typescript-mastery
版本 1.0.0
许可证
累计安装 4
当前安装数 4
历史版本数 1
常见问题

Typescript Mastery 是什么?

TypeScript advanced patterns — branded types, discriminated unions, template literals, generics, type guards, tsconfig optimization, and migration strategies. 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 754 次。

如何安装 Typescript Mastery?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install typescript-mastery」即可一键安装,无需额外配置。

Typescript Mastery 是免费的吗?

是的,Typescript Mastery 完全免费(开源免费),可自由下载、安装和使用。

Typescript Mastery 支持哪些平台?

Typescript Mastery 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Typescript Mastery?

由 msruruguay(@msruruguay)开发并维护,当前版本 v1.0.0。

💬 留言讨论