К основному содержанию
скилл CX Codex

jsdoc-typescript-docs — скилл для Claude Code: JSDoc и TypeDoc

Скилл расставляет JSDoc-комментарии в TypeScript-коде и собирает из них документацию через TypeDoc. Пригодится, когда проект оброс функциями без описаний.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add patricio0312rev/skills --skill jsdoc-typescript-docs -a claude-code
Открыть на GitHub

Что делает jsdoc-typescript-docs

Скилл ведёт по шагам: сначала документирует функции с параметрами, возвращаемым значением и примерами, потом интерфейсы, типы и перечисления, затем добавляет описания назначения и примеры кода. Отдельный шаг — генерация вывода TypeDoc и подключение сборки документации в CI.

Внутри есть готовые образцы для разных случаев: обычная функция, асинхронная с @throws, дженерик с @typeParam, перегрузки с @internal, интерфейсы с @default и @see, классы с @remarks. По ним видно, какие теги ставить и как оформлять примеры в блоках кода.

Скилл работает с TypeScript, поэтому на чистом JavaScript или в проекте без типов пользы от него мало. Для генерации документации нужен TypeDoc — если его в проекте нет, шаг с выводом документации придётся пропустить.

Какие задачи решает

  • расставить JSDoc-комментарии в файлах без описаний
  • описать параметры и возвращаемые значения функций
  • добавить примеры использования в комментарии
  • собрать HTML-документацию из комментариев через TypeDoc
  • подключить генерацию документации в CI

Примеры запросов агенту

  • задокументируй функции в src/api/client.ts через JSDoc
  • добавь JSDoc к интерфейсу User с примерами полей
  • настрой TypeDoc и собери документацию по проекту

Как установить jsdoc-typescript-docs

1Через Skills CLI (Vercel)

npx skills add patricio0312rev/skills --skill jsdoc-typescript-docs -a claude-code

2Вручную: положить файлы

~/.claude/skills/jsdoc-typescript-docs/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/jsdoc-typescript-docs/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора26

framer-motion-animator Скилл помогает создавать анимации и микроинтерфейсы на Framer Motion: от переходов между страницами до жестов свайпа и скролла. Пригодится при вёрстке интерактивных React-компонентов. CX Codex +1 11 100установок eslint-prettier-config Скилл разворачивает ESLint и Prettier в проекте на TypeScript и React: конфиги, правила, скрипты и хук на коммит. CX Codex +1 1 100установок changelog-writer Собирает CHANGELOG и release notes из git-коммитов, заголовков PR и ссылок на issues. Пригодится перед релизом, когда нужно разложить изменения по типам и подобрать версию. CX Codex +1 615установок bruno-collection-generator Скилл сканирует роуты Express, Next.js или Fastify и раскладывает их в коллекцию Bruno: по файлу .bru на запрос, с окружениями и авторизацией. CX Codex +1 603установок dockerfile-optimizer Скилл переписывает Dockerfile под многоэтапную сборку: меньше образ, быстрее сборка, кэш слоёв работает как надо. Пригодится, когда образ раздулся или сборка идёт по десять минут. CX Codex +1 530установок animation-micro-interaction-pack Набор готовых паттернов движения для интерфейса: ховеры, входы и выходы элементов, отклик на жесты. Пригодится, когда UI выглядит статично и хочется оживить его без ручного подбора таймингов. CX Codex +1 499установок explaining-code Разбирает незнакомый код по шагам: аналогия из быта, ASCII-схема потока, потом построчный разбор. Пригодится, когда чужой проект надо понять быстро. CX Codex +1 473установок conventional-commits Скилл пишет коммиты по спецификации Conventional Commits: тип, область, тело и футеры. Пригодится, когда нужен автоматический версионинг и changelog. CX Codex +1 469установок

Похожие

typescript-docs giuseppe-trisciuoglio Создаёт документацию TypeScript с JSDoc, TypeDoc и ADR. Пригодится для описания API, решений по архитектуре и кода на популярных фреймворках. CX Codex +1 4 200установок api-docs ruvnet Скилл собирает документацию по исходникам на TypeScript и JavaScript: находит публичные экспорты, разбирает JSDoc, дописывает недостающие комментарии и выдаёт OpenAPI 3.0 для HTTP-эндпоинтов. CX Codex +1 891установок update-docs NeoLabHQ Скилл анализирует изменения в коде через git и обновляет README, файлы docs/ или JSDoc. Помогает поддерживать документацию проекта без ручного переписывания. CX Codex +1 1 300установок typescript Mindrally Задаёт правила типизации и структуры кода на TypeScript для ассистента. Помогает писать функции короче 20 строк, заменять enums на maps и избегать any. CX Codex +1 955установок code-documentation aj-geddes Скилл для написания документации прямо в коде: JSDoc, Python-докстринги, JavaDoc, комментарии и описания API. Пригодится, когда нужно задокументировать функции и классы, а не переписывать их вслепую. CX Codex +1 492установок convex-docs convex Проверяет установленную в проекте версию Convex и подтягивает актуальную документацию в markdown вместо устаревшего кода из памяти модели. CX Codex +1 36 100установок

Рядом в теме «Тексты и документация»

Всё по теме «Тексты и документация» →

Вопросы о jsdoc-typescript-docs

Как установить jsdoc-typescript-docs в Claude?

Выполните npx skills add patricio0312rev/skills --skill jsdoc-typescript-docs -a claude-code. После этого файл скилла окажется в ~/.claude/skills/jsdoc-typescript-docs/SKILL.md.

Что делает jsdoc-typescript-docs?

Документирует TypeScript-код JSDoc-комментариями: параметры, возвращаемые значения, примеры, описания типов и интерфейсов. Дополнительно помогает собрать документацию через TypeDoc.

С какими языками работает скилл?

С TypeScript. Примеры в нём построены на типах, дженериках и перегрузках функций, так что для JavaScript без типизации эти шаблоны не подойдут.

Исходный текст

SKILL.md · MIT
---
name: jsdoc-typescript-docs
description: Documents TypeScript code with JSDoc comments, generates API documentation, and creates type-safe documentation. Use when users request "JSDoc", "code documentation", "API docs", "TypeDoc", or "inline documentation".
---

# JSDoc TypeScript Documentation

Create comprehensive inline documentation for TypeScript codebases.

## Core Workflow

1. **Document functions**: Parameters, returns, examples
2. **Document types**: Interfaces, types, enums
3. **Add descriptions**: Purpose and usage
4. **Include examples**: Code samples
5. **Generate docs**: TypeDoc output
6. **Integrate CI**: Automated doc generation

## Function Documentation

### Basic Function

```typescript
/**
 * Calculates the total price including tax.
 *
 * @param price - The base price before tax
 * @param taxRate - The tax rate as a decimal (e.g., 0.08 for 8%)
 * @returns The total price including tax
 *
 * @example
 * ```typescript
 * const total = calculateTotal(100, 0.08);
 * console.log(total); // 108
 * ```
 */
export function calculateTotal(price: number, taxRate: number): number {
  return price * (1 + taxRate);
}
```

### Async Function

```typescript
/**
 * Fetches user data from the API.
 *
 * @param userId - The unique identifier of the user
 * @param options - Optional configuration for the request
 * @returns A promise that resolves to the user data
 *
 * @throws {NotFoundError} When the user doesn't exist
 * @throws {NetworkError} When the request fails
 *
 * @example
 * ```typescript
 * try {
 *   const user = await fetchUser('user-123');
 *   console.log(user.name);
 * } catch (error) {
 *   if (error instanceof NotFoundError) {
 *     console.log('User not found');
 *   }
 * }
 * ```
 */
export async function fetchUser(
  userId: string,
  options?: FetchOptions
): Promise<User> {
  const response = await fetch(`/api/users/${userId}`, options);

  if (response.status === 404) {
    throw new NotFoundError(`User ${userId} not found`);
  }

  if (!response.ok) {
    throw new NetworkError('Failed to fetch user');
  }

  return response.json();
}
```

### Generic Function

```typescript
/**
 * Filters an array based on a predicate function.
 *
 * @typeParam T - The type of elements in the array
 * @param array - The array to filter
 * @param predicate - A function that returns true for elements to keep
 * @returns A new array containing only elements that pass the predicate
 *
 * @example
 * ```typescript
 * const numbers = [1, 2, 3, 4, 5];
 * const evens = filterArray(numbers, n => n % 2 === 0);
 * // evens: [2, 4]
 * ```
 */
export function filterArray<T>(
  array: T[],
  predicate: (item: T, index: number) => boolean
): T[] {
  return array.filter(predicate);
}
```

### Overloaded Function

```typescript
/**
 * Formats a value for display.
 *
 * @param value - The value to format
 * @returns The formatted string
 */
export function format(value: number): string;
/**
 * Formats a value with a specific format string.
 *
 * @param value - The value to format
 * @param formatStr - The format string (e.g., 'currency', 'percent')
 * @returns The formatted string
 */
export function format(value: number, formatStr: string): string;
/**
 * @internal
 */
export function format(value: number, formatStr?: string): string {
  if (formatStr === 'currency') {
    return `$${value.toFixed(2)}`;
  }
  if (formatStr === 'percent') {
    return `${(value * 100).toFixed(1)}%`;
  }
  return value.toString();
}
```

## Interface Documentation

```typescript
/**
 * Represents a user in the system.
 *
 * @example
 * ```typescript
 * const user: User = {
 *   id: 'user-123',
 *   email: '[email protected]',
 *   name: 'John Doe',
 *   role: 'admin',
 *   createdAt: new Date(),
 * };
 * ```
 */
export interface User {
  /**
   * The unique identifier for the user.
   * @example 'user-123'
   */
  id: string;

  /**
   * The user's email address.
   * @example '[email protected]'
   */
  email: string;

  /**
   * The user's display name.
   * @example 'John Doe'
   */
  name: string;

  /**
   * The user's role in the system.
   * @default 'user'
   */
  role: 'admin' | 'user' | 'guest';

  /**
   * When the user account was created.
   */
  createdAt: Date;

  /**
   * When the user account was last updated.
   * @optional
   */
  updatedAt?: Date;

  /**
   * The user's profile settings.
   * @see {@link UserProfile}
   */
  profile?: UserProfile;
}

/**
 * User profile configuration.
 */
export interface UserProfile {
  /** URL to the user's avatar image */
  avatarUrl?: string;

  /** User's preferred language code (e.g., 'en', 'es') */
  language: string;

  /** User's timezone (e.g., 'America/New_York') */
  timezone: string;

  /** User notification preferences */
  notifications: NotificationSettings;
}
```

## Type Documentation

```typescript
/**
 * HTTP methods supported by the API.
 */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';

/**
 * Configuration options for API requests.
 *
 * @typeParam TBody - The type of the request body
 */
export type RequestConfig<TBody = unknown> = {
  /** HTTP method to use */
  method: HttpMethod;

  /** Request headers */
  headers?: Record<string, string>;

  /** Request body (for POST, PUT, PATCH) */
  body?: TBody;

  /** Request timeout in milliseconds */
  timeout?: number;

  /** Number of retry attempts on failure */
  retries?: number;
};

/**
 * Result type for operations that can fail.
 *
 * @typeParam T - The type of the success value
 * @typeParam E - The type of the error value
 *
 * @example
 * ```typescript
 * function divide(a: number, b: number): Result<number, string> {
 *   if (b === 0) {
 *     return { success: false, error: 'Division by zero' };
 *   }
 *   return { success: true, data: a / b };
 * }
 * ```
 */
export type Result<T, E = Error> =
  | { success: true; data: T }
  | { success: false; error: E };
```

## Class Documentation

```typescript
/**
 * A client for interacting with the API.
 *
 * @remarks
 * This client handles authentication, retries, and error handling
 * automatically. Use the {@link ApiClient.create} factory method
 * to create an instance.
 *
 * @example
 * ```typescript
 * const client = ApiClient.create({
 *   baseUrl: 'https://api.example.com',
 *   apiKey: process.env.API_KEY,
 * });
 *
 * const users = await client.get<User[]>('/users');
 * ```
 */
export class ApiClient {
  /**
   * The base URL for all API requests.
   * @readonly
   */
  readonly baseUrl: string;

  /**
   * Creates a new ApiClient instance.
   *
   * @param config - The client configuration
   * @returns A new ApiClient instance
   *
   * @example
   * ```typescript
   * const client = ApiClient.create({ baseUrl: 'https://api.example.com' });
   * ```
   */
  static create(config: ApiClientConfig): ApiClient {
    return new ApiClient(config);
  }

  /**
   * @internal
   */
  private constructor(private config: ApiClientConfig) {
    this.baseUrl = config.baseUrl;
  }

  /**
   * Performs a GET request.
   *
   * @typeParam T - The expected response type
   * @param endpoint - The API endpoint (relative to baseUrl)
   * @param options - Optional request configuration
   * @returns A promise that resolves to the response data
   *
   * @throws {ApiError} When the request fails
   *
   * @example
   * ```typescript
   * interface User { id: string; name: string; }
   * const users = await client.get<User[]>('/users');
   * ```
   */
  async get<T>(endpoint: string, options?: RequestOptions): Promise<T> {
    return this.request<T>('GET', endpoint, options);
  }

  /**
   * Performs a POST request.
   *
   * @typeParam T - The expected response type
   * @typeParam TBody - The request body type
   * @param endpoint - The API endpoint
   * @param body - The request body
   * @param options - Optional request configuration
   * @returns A promise that resolves to the response data
   */
  async post<T, TBody = unknown>(
    endpoint: string,
    body: TBody,
    options?: RequestOptions
  ): Promise<T> {
    return this.request<T>('POST', endpoint, { ...options, body });
  }

  /**
   * @internal
   */
  private async request<T>(
    method: HttpMethod,
    endpoint: string,
    options?: RequestOptions
  ): Promise<T> {
    // Implementation
  }
}
```

## Enum Documentation

```typescript
/**
 * Status codes for order processing.
 *
 * @remarks
 * Orders progress through these statuses in sequence,
 * though they may skip directly to `Cancelled` from any state.
 */
export enum OrderStatus {
  /** Order has been created but not yet processed */
  Pending = 'pending',

  /** Payment has been received and order is being prepared */
  Processing = 'processing',

  /** Order has been shipped to the customer */
  Shipped = 'shipped',

  /** Order has been delivered to the customer */
  Delivered = 'delivered',

  /** Order has been cancelled */
  Cancelled = 'cancelled',

  /** Order has been returned by the customer */
  Returned = 'returned',
}
```

## React Component Documentation

```typescript
/**
 * A customizable button component.
 *
 * @remarks
 * This button supports multiple variants, sizes, and states.
 * It is fully accessible and supports keyboard navigation.
 *
 * @example
 * ```tsx
 * // Basic usage
 * <Button onClick={handleClick}>Click me</Button>
 *
 * // With variant and size
 * <Button variant="secondary" size="lg">
 *   Large Secondary Button
 * </Button>
 *
 * // Loading state
 * <Button loading>Submitting...</Button>
 * ```
 */
export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  /**
   * The visual style variant.
   * @default 'primary'
   */
  variant?: 'primary' | 'secondary' | 'outline' | 'ghost';

  /**
   * The size of the button.
   * @default 'md'
   */
  size?: 'sm' | 'md' | 'lg';

  /**
   * Whether the button is in a loading state.
   * When true, the button is disabled and shows a spinner.
   * @default false
   */
  loading?: boolean;

  /**
   * Icon to display before the button text.
   */
  leftIcon?: React.ReactNode;

  /**
   * Icon to display after the button text.
   */
  rightIcon?: React.ReactNode;
}

/**
 * A customizable button component.
 *
 * @param props - The component props
 * @returns The rendered button element
 *
 * @see {@link ButtonProps} for available props
 */
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ variant = 'primary', size = 'md', loading, children, ...props }, ref) => {
    // Implementation
  }
);

Button.displayName = 'Button';
```

## TypeDoc Configuration

```json
// typedoc.json
{
  "entryPoints": ["./src/index.ts"],
  "out": "./docs",
  "name": "My Library",
  "readme": "./README.md",
  "plugin": [
    "typedoc-plugin-markdown",
    "typedoc-plugin-mdn-links"
  ],
  "excludePrivate": true,
  "excludeProtected": true,
  "excludeInternal": true,
  "includeVersion": true,
  "categorizeByGroup": true,
  "categoryOrder": ["Core", "Utilities", "Types", "*"],
  "navigationLinks": {
    "GitHub": "https://github.com/user/repo",
    "npm": "https://www.npmjs.com/package/my-package"
  },
  "validation": {
    "notExported": true,
    "invalidLink": true,
    "notDocumented": false
  }
}
```

```json
// package.json
{
  "scripts": {
    "docs": "typedoc",
    "docs:watch": "typedoc --watch"
  },
  "devDependencies": {
    "typedoc": "^0.25.0",
    "typedoc-plugin-markdown": "^3.17.0",
    "typedoc-plugin-mdn-links": "^3.1.0"
  }
}
```

## JSDoc Tags Reference

```typescript
/**
 * Summary description.
 *
 * @remarks
 * Additional details and implementation notes.
 *
 * @param name - Parameter description
 * @typeParam T - Type parameter description
 * @returns Return value description
 *
 * @throws {ErrorType} When error condition
 *
 * @example
 * ```typescript
 * // Example code
 * ```
 *
 * @see {@link RelatedItem} for related documentation
 * @see https://example.com External link
 *
 * @deprecated Use `newFunction` instead
 * @since 1.0.0
 * @version 2.0.0
 *
 * @alpha - Early preview
 * @beta - Feature complete but may change
 * @public - Stable API
 * @internal - Not for public use
 * @readonly - Cannot be modified
 * @virtual - Can be overridden
 * @override - Overrides parent
 * @sealed - Cannot be extended
 *
 * @defaultValue default value
 * @eventProperty - For event properties
 */
```

## Best Practices

1. **Document public API**: All exports need docs
2. **Use examples**: Show real usage
3. **Describe parameters**: Clear, concise descriptions
4. **Document errors**: What can be thrown
5. **Link related items**: Use @see tags
6. **Keep updated**: Sync docs with code
7. **Generate HTML**: TypeDoc for browsable docs
8. **Validate in CI**: Check for missing docs

## Output Checklist

Every documented codebase should include:

- [ ] All public functions documented
- [ ] All interfaces and types documented
- [ ] All parameters described
- [ ] Return values documented
- [ ] Examples for complex functions
- [ ] Thrown errors documented
- [ ] TypeDoc configuration
- [ ] Generated documentation
- [ ] Documentation in CI pipeline
- [ ] README with API overview

© patricio0312rev · MIT · patricio0312rev/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой