Token导航 LogoToken导航TokenDH.com
开发规范需要联网github未标认证来源可访问clear审计通过

typescript-best-practicesTypeScript 最佳实践

Agent Skill

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

总安装

8,303

周安装

353

GitHub Stars

69

下载量

2,909
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/jwynia/agent-skills --skill typescript-best-practices

简介

typescript-best-practices 处理 GitHub 仓库、Issue 和 Pull Request 协作信息。

  • 适合围绕代码变更、仓库状态和协作事项进行整理与分析。
  • 通过 npx skills add 命令从 GitHub 仓库安装并使用。
  • 安装前需确认权限范围、维护状态及是否触发联网或文件操作。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

TypeScript Best Practices

Guide AI agents in writing high-quality TypeScript code. This skill provides coding standards, architecture patterns, and tools for analysis and scaffolding.

When to Use This Skill

Use this skill when:

  • Generating new TypeScript code
  • Reviewing TypeScript files for quality issues
  • Creating new modules, services, or components
  • Refactoring JavaScript to TypeScript
  • Answering questions about TypeScript patterns or types
  • Designing APIs or interfaces

Do NOT use this skill when:

  • Working with pure JavaScript (no TypeScript)
  • Debugging runtime errors (use debugging tools)
  • Framework-specific patterns (React, Vue, etc. - use framework skills)

Core Principles

1. Type Safety First

Maximize compile-time error detection:

// Prefer unknown over any for unknown types
function processInput(data: unknown): string {
  if (typeof data === "string") return data;
  if (typeof data === "number") return String(data);
  throw new Error("Unsupported type");
}

// Explicit return types for public APIs
export function calculateTotal(items: ReadonlyArray<Item>): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// Use const assertions for literal types
const CONFIG = {
  mode: "production",
  version: 1,
} as const;

2. Immutability by Default

Prevent accidental mutations:

// Use readonly for object properties
interface User {
  readonly id: string;
  readonly email: string;
  name: string; // Only mutable if intentional
}

// Use ReadonlyArray for collections
function processItems(items: ReadonlyArray<Item>): ReadonlyArray<Result> {
  return items.map(transform);
}

// Prefer spreading over mutation
function updateUser(user: User, name: string): User {
  return { ...user, name };
}

3. Error Handling with Types

Use the type system for error handling:

// Result type for recoverable errors
type Result<T, E = Error> =
  | { success: true; value: T }
  | { success: false; error: E };

// Typed error classes
class ValidationError extends Error {
  constructor(
    message: string,
    readonly field: string,
    readonly code: string
  ) {
    super(message);
    this.name = "ValidationError";
  }
}

// Function with Result return type
function parseConfig(input: string): Result<Config, ValidationError> {
  try {
    const data = JSON.parse(input);
    if (!isValidConfig(data)) {
      return {
        success: false,
        error: new ValidationError("Invalid config", "root", "INVALID_FORMAT"),
      };
    }
    return { success: true, value: data };
  } catch {
    return {
      success: false,
      error: new ValidationError("Parse failed", "root", "PARSE_ERROR"),
    };
  }
}

4. Code Organization

Structure code for maintainability:

// One concept per file
// user.ts - User type and related utilities
export interface User {
  readonly id: string;
  readonly email: string;
  readonly createdAt: Date;
}

export function createUser(email: string): User {
  return {
    id: crypto.randomUUID(),
    email,
    createdAt: new Date(),
  };
}

// Explicit exports (no barrel file wildcards)
// index.ts
export { User, createUser } from "./user.ts";
export { validateEmail } from "./validation.ts";

Quick Reference

CategoryPreferAvoid
Unknown typesunknownany
CollectionsReadonlyArray<T>T[] for inputs
ObjectsReadonly<T>Mutable by default
Null checksOptional chaining ?.!= null
Type narrowingType guardsas assertions
Return typesExplicit on exportsInferred on exports
EnumsString literal unionsNumeric enums
ImportsNamed importsDefault imports
ErrorsResult typesThrowing for flow control
Loopsfor...of, .map()for...in on arrays

Code Generation Guidelines

When generating TypeScript code, follow these patterns:

Module Structure

/**
 * Module description
 * @module module-name
 */

// === Types ===
export interface ModuleOptions {
  readonly setting: string;
}

export interface ModuleResult {
  readonly data: unknown;
}

// === Constants ===
const DEFAULT_OPTIONS: ModuleOptions = {
  setting: "default",
};

// === Implementation ===
export function processData(
  input: unknown,
  options: Partial<ModuleOptions> = {}
): ModuleResult {
  const opts = { ...DEFAULT_OPTIONS, ...options };
  // Implementation
  return { data: input };
}

Function Design

// Pure functions preferred
function transform(input: Input): Output {
  // No side effects, same input = same output
  return { ...input, processed: true };
}

// Explicit parameter types
function fetchUser(id: string, options?: FetchOptions): Promise<User> {
  // Implementation
}

// Use function overloads for complex signatures
function parse(input: string): ParsedData;
function parse(input: Buffer): ParsedData;
function parse(input: string | Buffer): ParsedData {
  // Implementation
}

Interface Design

// Prefer interfaces for object shapes
interface UserData {
  readonly id: string;
  readonly email: string;
}

// Use type for unions and intersections
type UserRole = "admin" | "user" | "guest";
type AdminUser = UserData & { readonly role: "admin" };

// Document with JSDoc
/**
 * Configuration for the API client
 * @property baseUrl - The base URL for API requests
 * @property timeout - Request timeout in milliseconds
 */
interface ApiConfig {
  readonly baseUrl: string;
  readonly timeout?: number;
}

Common Anti-Patterns

Avoid these patterns when generating code:

Anti-PatternProblemSolution
any typeDisables type checkingUse unknown and narrow
as assertionsRuntime errorsUse type guards
Non-null !Null pointer errorsOptional chaining ?.
Mutable paramsUnexpected mutationsReadonly<T>
Magic stringsTypos, no autocompleteString literal types
God classesHard to test/maintainSingle responsibility
Circular depsBuild/runtime issuesDependency inversion
Index signaturesLose type infoExplicit properties

See references/anti-patterns/common-mistakes.md for detailed examples.

Scripts Reference

analyze.ts

Analyze TypeScript code for quality issues:

deno run --allow-read scripts/analyze.ts <path> [options]

Options:
  --strict        Enable all checks
  --json          Output JSON for programmatic use
  --fix-hints     Show suggested fixes

Examples:
  # Analyze a file
  deno run --allow-read scripts/analyze.ts ./src/utils.ts

  # Analyze directory with strict mode
  deno run --allow-read scripts/analyze.ts ./src --strict

  # JSON output for CI
  deno run --allow-read scripts/analyze.ts ./src --json

generate-types.ts

Generate TypeScript types from JSON data:

deno run --allow-read --allow-write scripts/generate-types.ts <input> [options]

Options:
  --name <name>   Root type name (default: inferred)
  --output <path> Output file path
  --readonly      Generate readonly types
  --interface     Use interface instead of type

Examples:
  # Generate from JSON file
  deno run --allow-read scripts/generate-types.ts ./data.json --name Config

  # Generate readonly interface
  deno run --allow-read --allow-write scripts/generate-types.ts ./api-response.json \
    --interface --readonly --output ./types/api.ts

scaffold-module.ts

Create properly structured TypeScript modules:

deno run --allow-read --allow-write scripts/scaffold-module.ts [options]

Options:
  --name <name>   Module name (required)
  --path <path>   Target directory (default: ./src)
  --type <type>   Type: service, util, component
  --with-tests    Include test file

Examples:
  # Create a utility module
  deno run --allow-read --allow-write scripts/scaffold-module.ts \
    --name "string-utils" --type util

  # Create a service with tests
  deno run --allow-read --allow-write scripts/scaffold-module.ts \
    --name "user-service" --type service --with-tests

Additional Resources

Type System Deep Dives

  • references/type-system/advanced-types.md - Generics, conditional types, mapped types
  • references/type-system/type-guards.md - Type narrowing techniques
  • references/type-system/utility-types.md - Built-in utility types

Pattern Guides

  • references/patterns/error-handling.md - Result types, typed errors
  • references/patterns/async-patterns.md - Async/await best practices
  • references/patterns/functional-patterns.md - Immutability, composition
  • references/patterns/module-patterns.md - Exports, dependency injection

Architecture

  • references/architecture/project-structure.md - Directory organization
  • references/architecture/api-design.md - Interface design, versioning

Templates

  • assets/templates/module-template.ts.md - Module starter template
  • assets/templates/service-template.ts.md - Service class template
  • assets/tsconfig-presets/strict.json - Maximum strictness config
  • assets/tsconfig-presets/recommended.json - Balanced defaults

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

29.47%
按下载量换算857

OpenCode

22.59%
按下载量换算657

Antigravity

16.49%
按下载量换算480

Gemini CLI

13.75%
按下载量换算400

Codex

7.41%
按下载量换算216

Cursor

3.34%
按下载量换算97

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills