AgentSkillsCN

JavaScript

当用户提出“编写 JavaScript”、“创建 JS 模块”、“实现 JS 类”、“使用 JSDoc 编写这段代码”、“添加 JSDoc 注释”、“添加类型注解”、“对这种类型进行建模”、“使用现代 JavaScript”、“转换为 ESM”、“采用 ES 模块”、“修复这段 JavaScript”、“重构这段 JS 代码”,或任何涉及编写、审查或优化 JavaScript 代码的任务时,都应使用此技能。本技能将为您提供基于 JSDoc 的类型建模最佳实践,以及在现代语言特性(ES2024/2025)、Web API、错误处理和模块化模式等方面的指导。本技能涵盖的是经过 TypeScript 检查的 JSDoc 语法的纯 JavaScript,而非 TypeScript 文件(.ts)。

SKILL.md
--- frontmatter
name: JavaScript
version: 0.1.0
description: >-
  This skill should be used when the user asks to "write JavaScript",
  "create a JS module", "implement a JS class", "type this with JSDoc",
  "add JSDoc comments", "add type annotations", "model this type",
  "use modern JS", "convert to ESM", "use ES modules",
  "fix this JavaScript", "refactor this JS code", or any task
  involving writing, reviewing, or improving JavaScript code.
  Provides best practices for type modeling with JSDoc, modern
  language features (ES2024/2025), web APIs, error handling, and
  module patterns. This skill covers plain JavaScript with
  TypeScript-checked JSDoc, NOT TypeScript (.ts) files.

JavaScript

Best practices for writing modern, type-safe JavaScript using JSDoc annotations checked by TypeScript. Covers type modeling, modern language features (ES2024/2025), web APIs, error handling, and module patterns.

This skill targets plain .js files with checkJs: true in jsconfig.json. It does not cover TypeScript .ts files.

Project Setup

jsconfig.json

Every JS project using typed JSDoc should have a jsconfig.json:

json
{
  "compilerOptions": {
    "checkJs": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "target": "ES2024",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "noEmit": true
  },
  "include": ["src/**/*.js"],
  "exclude": ["node_modules"]
}

Adjust target, module, and moduleResolution to match the project's runtime environment. Run type checking with tsc --project jsconfig.json or integrate into CI. TypeScript 5.5+ is recommended for full JSDoc support including @import.

Type Modeling with JSDoc

Core Annotations

Use these JSDoc tags for type safety. TypeScript's checker understands them natively.

TagPurposeExample
@typeInline type annotation/** @type {string} */
@param / @returnsFunction signatures@param {number} x
@typedef + @propertyNamed object typesSee below
@templateGeneric type parameters@template T
@callbackFunction type definitionsNamed function signatures
@importClean type imports (TS 5.5+)/** @import { Foo } from './types.js' */
@satisfiesValidate type, preserve inference (TS 5.0+)/** @satisfies {Config} */
@overloadMultiple function signatures (TS 5.0+)See references/type-patterns.md

Defining Types

js
/**
 * @typedef {Object} ElevatorState
 * @property {number} index
 * @property {number | null} destinationFloor
 * @property {'idle' | 'moving' | 'stopped'} status
 */

Importing Types

Prefer the @import tag (TS 5.5+) over inline import() expressions:

js
/** @import { ElevatorState, FloorConfig } from './types.js' */

Older pattern (still works, more verbose):

js
/** @type {import('./types.js').ElevatorState} */

Discriminated Unions

Model variant types using a shared discriminant property:

js
/**
 * @typedef {{ kind: 'success', value: unknown }} Success
 * @typedef {{ kind: 'error', error: Error }} Failure
 * @typedef {Success | Failure} Result
 */

/** @param {Result} result */
function handle(result) {
  if (result.kind === 'success') {
    // Narrowed to Success
    console.log(result.value);
  }
}

TypeScript's control flow analysis narrows union types in JS files through typeof, instanceof, in, equality checks, and truthiness checks — no TypeScript syntax required.

Generic Types

js
/**
 * @template T
 * @param {Promise<T>} promise
 * @returns {Promise<{ data: T, error: null } | { data: null, error: Error }>}
 */
async function tryCatch(promise) {
  try {
    return { data: await promise, error: null };
  } catch (e) {
    return { data: null, error: /** @type {Error} */ (e) };
  }
}

Use @template {Constraint} T for bounded generics:

js
/**
 * @template {string} K
 * @template V
 * @param {Record<K, V>} obj
 * @param {K} key
 * @returns {V}
 */
function getProperty(obj, key) {
  return obj[key];
}

Error Suppression

Prefer // @ts-expect-error over // @ts-ignore. The former errors when the underlying issue is fixed, preventing stale suppressions.

Forward Compatibility

TypeScript 7 ("Corsa"), as announced, will drop @enum and @constructor tags. Use ES classes and string literal unions instead. Avoid relying on these patterns in new code.

For detailed patterns including branded types, overloads, and complex generics, consult references/type-patterns.md.

Modern Language Features

ES2024 (Stable)

FeatureUse Case
Promise.withResolvers()Extract resolve/reject from promise scope
Object.groupBy() / Map.groupBy()Group array items by computed key
ArrayBuffer.transfer()Transfer buffer ownership without copying
String.isWellFormed() / toWellFormed()Validate/fix Unicode strings
RegExp /v flagSet notation in character classes

ES2025 (Stable)

FeatureUse Case
Set methodsunion(), intersection(), difference(), symmetricDifference(), isSubsetOf(), isSupersetOf(), isDisjointFrom()
Iterator helpers.map(), .filter(), .take(), .drop(), .flatMap(), .reduce(), .toArray() on iterators
Promise.try()Wrap sync-or-async function in a promise
Import attributesimport data from './config.json' with { type: 'json' }
RegExp.escape()Escape special regex characters

Emerging (Stage 3-4, Check Engine Support)

FeatureStatusNotes
Temporal APIStage 3Chrome 144+, Firefox 139+. No Safari. Use polyfill if needed.
using / Explicit Resource ManagementStage 3Chrome 134+. Not yet cross-browser.
Error.isError()Stage 4, ES2026Cross-realm Error detection
import deferStage 4, ES2026Lazy module evaluation

Prefer stable features. For Stage 3 features, check target runtime support before adopting.

Web APIs

AbortController Patterns

Use AbortController for cancellation and cleanup across async operations, event listeners, and resource management:

js
const controller = new AbortController();

// Combine user cancellation with timeout
const signal = AbortSignal.any([
  controller.signal,
  AbortSignal.timeout(5000)
]);

try {
  const response = await fetch(url, { signal });
} catch (err) {
  if (err.name === 'TimeoutError') { /* timed out */ }
  else if (err.name === 'AbortError') { /* user cancelled */ }
  else throw err;
}

Use AbortSignal with addEventListener for automatic listener cleanup:

js
element.addEventListener('click', handler, { signal: controller.signal });
// Later: controller.abort() removes the listener

Other Stable APIs

APIUse Case
structuredClone(obj)Deep clone objects (handles Date, Map, Set, ArrayBuffer)
CustomEvent / EventTargetEvent-driven architecture without frameworks
crypto.randomUUID()Generate UUIDs
navigator.sendBeacon()Reliable analytics/telemetry on page unload
URL / URLSearchParamsURL manipulation without string hacking
TextEncoder / TextDecoderString-to-bytes conversion
ReadableStream / WritableStreamStreaming data processing
BroadcastChannelCross-tab communication

Error Handling

Error Cause Chains

Wrap errors with context using the cause option:

js
try {
  const data = JSON.parse(raw);
} catch (err) {
  throw new Error('Failed to parse config', { cause: err });
}

AggregateError

Group multiple errors from parallel operations:

js
const errors = [];
for (const task of tasks) {
  try { await task(); } catch (e) { errors.push(e); }
}
if (errors.length) {
  throw new AggregateError(errors, 'Multiple tasks failed');
}

Pattern Summary

PatternWhen
Error + causeWrapping a single error with added context
AggregateErrorGrouping multiple independent errors
AbortError / TimeoutErrorCancellation and timeout signaling

Module Patterns

ESM Conventions

  • Use "type": "module" in package.json
  • Prefer named exports over default exports for discoverability
  • Use the "exports" field to define the package's public API
  • Avoid barrel files (index.js re-exporting everything) — they degrade tree-shaking and increase load time
  • Prefer direct imports: import { thing } from './utils/thing.js'

Dynamic Imports

Use import() for code splitting and conditional loading:

js
const { handler } = await import(`./handlers/${type}.js`);

Class Patterns

Use private fields (#field) for encapsulation:

js
class Elevator {
  /** @type {number} */
  #currentFloor;

  /** @type {number | null} */
  #destination = null;

  /**
   * @param {number} startFloor
   */
  constructor(startFloor) {
    this.#currentFloor = startFloor;
  }

  get currentFloor() {
    return this.#currentFloor;
  }
}

Separate internal state from public API surfaces using toJSON() for serialization and purpose-built API methods for external consumers.

Additional Resources

  • references/type-patterns.md — Advanced JSDoc type patterns: branded types, overloads, complex generics, conditional patterns, and TS 7 migration guidance.
  • references/api-reference.md — Quick reference for modern Web APIs and ES2024/2025 features with usage examples and browser/runtime support status.