jsdoc-typescript-docs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJSDoc TypeScript Documentation
JSDoc TypeScript 文档编写
Create comprehensive inline documentation for TypeScript codebases.
为TypeScript代码库创建全面的内联文档。
Core Workflow
核心流程
- Document functions: Parameters, returns, examples
- Document types: Interfaces, types, enums
- Add descriptions: Purpose and usage
- Include examples: Code samples
- Generate docs: TypeDoc output
- Integrate CI: Automated doc generation
- 为函数编写文档:参数、返回值、示例
- 为类型编写文档:接口、类型、枚举
- 添加描述信息:用途与使用方式
- 包含示例代码:代码样例
- 生成文档:TypeDoc输出结果
- 集成CI流程:自动化文档生成
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);
}typescript
/**
* 计算包含税费的总价。
*
* @param price - 税前基础价格
* @param taxRate - 税率(小数形式,例如8%对应0.08)
* @returns 包含税费的总价
*
* @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();
}typescript
/**
* 从API获取用户数据。
*
* @param userId - 用户的唯一标识符
* @param options - 请求的可选配置项
* @returns 解析为用户数据的Promise
*
* @throws {NotFoundError} 当用户不存在时抛出
* @throws {NetworkError} 当请求失败时抛出
*
* @example
* ```typescript
* try {
* const user = await fetchUser('user-123');
* console.log(user.name);
* } catch (error) {
* if (error instanceof NotFoundError) {
* console.log('用户不存在');
* }
* }
* ```
*/
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);
}typescript
/**
* 根据断言函数过滤数组。
*
* @typeParam T - 数组中元素的类型
* @param array - 待过滤的数组
* @param predicate - 返回true表示保留对应元素的函数
* @returns 仅包含通过断言的元素的新数组
*
* @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();
}typescript
/**
* 格式化值用于展示。
*
* @param value - 待格式化的值
* @returns 格式化后的字符串
*/
export function format(value: number): string;
/**
* 使用指定的格式字符串格式化值。
*
* @param value - 待格式化的值
* @param formatStr - 格式字符串(例如'currency'、'percent')
* @returns 格式化后的字符串
*/
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: 'john@example.com',
* 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 'john@example.com'
*/
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;
}typescript
/**
* 表示系统中的用户。
*
* @example
* ```typescript
* const user: User = {
* id: 'user-123',
* email: 'john@example.com',
* name: 'John Doe',
* role: 'admin',
* createdAt: new Date(),
* };
* ```
*/
export interface User {
/**
* 用户的唯一标识符。
* @example 'user-123'
*/
id: string;
/**
* 用户的邮箱地址。
* @example 'john@example.com'
*/
email: string;
/**
* 用户的显示名称。
* @example 'John Doe'
*/
name: string;
/**
* 用户在系统中的角色。
* @default 'user'
*/
role: 'admin' | 'user' | 'guest';
/**
* 用户账户的创建时间。
*/
createdAt: Date;
/**
* 用户账户的最后更新时间。
* @optional
*/
updatedAt?: Date;
/**
* 用户的配置文件设置。
* @see {@link UserProfile}
*/
profile?: UserProfile;
}
/**
* 用户配置文件的配置项。
*/
export interface UserProfile {
/** 用户头像图片的URL */
avatarUrl?: string;
/** 用户偏好的语言代码(例如'en'、'es') */
language: string;
/** 用户的时区(例如'America/New_York') */
timezone: string;
/** 用户的通知偏好设置 */
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 };typescript
/**
* API支持的HTTP方法。
*/
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
/**
* API请求的配置选项。
*
* @typeParam TBody - 请求体的类型
*/
export type RequestConfig<TBody = unknown> = {
/** 使用的HTTP方法 */
method: HttpMethod;
/** 请求头 */
headers?: Record<string, string>;
/** 请求体(适用于POST、PUT、PATCH请求) */
body?: TBody;
/** 请求超时时间(毫秒) */
timeout?: number;
/** 请求失败后的重试次数 */
retries?: number;
};
/**
* 可能失败的操作的结果类型。
*
* @typeParam T - 成功返回值的类型
* @typeParam E - 错误返回值的类型
*
* @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
}
}typescript
/**
* 用于与API交互的客户端。
*
* @remarks
* 该客户端自动处理认证、重试和错误处理。使用{@link ApiClient.create}工厂方法
* 创建实例。
*
* @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 {
/**
* 所有API请求的基础URL。
* @readonly
*/
readonly baseUrl: string;
/**
* 创建一个新的ApiClient实例。
*
* @param config - 客户端配置项
* @returns 新的ApiClient实例
*
* @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;
}
/**
* 执行GET请求。
*
* @typeParam T - 预期的响应类型
* @param endpoint - API端点(相对于baseUrl)
* @param options - 可选的请求配置项
* @returns 解析为响应数据的Promise
*
* @throws {ApiError} 当请求失败时抛出
*
* @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);
}
/**
* 执行POST请求。
*
* @typeParam T - 预期的响应类型
* @typeParam TBody - 请求体的类型
* @param endpoint - API端点
* @param body - 请求体
* @param options - 可选的请求配置项
* @returns 解析为响应数据的Promise
*/
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> {
// 实现代码
}
}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',
}typescript
/**
* 订单处理的状态码。
*
* @remarks
* 订单会按顺序经历这些状态,但也可以从任意状态直接跳转到`Cancelled`。
*/
export enum OrderStatus {
/** 订单已创建但尚未处理 */
Pending = 'pending',
/** 已收到付款,订单正在处理中 */
Processing = 'processing',
/** 订单已发货给客户 */
Shipped = 'shipped',
/** 订单已交付给客户 */
Delivered = 'delivered',
/** 订单已取消 */
Cancelled = 'cancelled',
/** 订单已被客户退回 */
Returned = 'returned',
}React Component Documentation
React组件文档示例
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';typescript
/**
* 可自定义的按钮组件。
*
* @remarks
* 该按钮支持多种变体、尺寸和状态。
* 完全支持无障碍访问和键盘导航。
*
* @example
* ```tsx
* // 基础用法
* <Button onClick={handleClick}>点击我</Button>
*
* // 指定变体和尺寸
* <Button variant="secondary" size="lg">
* 大型次要按钮
* </Button>
*
* // 加载状态
* <Button loading>提交中...</Button>
* ```
*/
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
/**
* 视觉样式变体。
* @default 'primary'
*/
variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
/**
* 按钮的尺寸。
* @default 'md'
*/
size?: 'sm' | 'md' | 'lg';
/**
* 按钮是否处于加载状态。
* 为true时,按钮会被禁用并显示加载动画。
* @default false
*/
loading?: boolean;
/**
* 显示在按钮文本左侧的图标。
*/
leftIcon?: React.ReactNode;
/**
* 显示在按钮文本右侧的图标。
*/
rightIcon?: React.ReactNode;
}
/**
* 可自定义的按钮组件。
*
* @param props - 组件的属性
* @returns 渲染后的按钮元素
*
* @see {@link ButtonProps} 查看可用属性
*/
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ variant = 'primary', size = 'md', loading, children, ...props }, ref) => {
// 实现代码
}
);
Button.displayName = 'Button';TypeDoc Configuration
TypeDoc配置
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"
}
}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
JSDoc标签参考
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
*/typescript
/**
* 摘要描述。
*
* @remarks
* 额外的细节和实现说明。
*
* @param name - 参数描述
* @typeParam T - 类型参数描述
* @returns 返回值描述
*
* @throws {ErrorType} 触发错误的条件
*
* @example
* ```typescript
* // 示例代码
* ```
*
* @see {@link RelatedItem} 查看相关文档
* @see https://example.com 外部链接
*
* @deprecated 请改用`newFunction`
* @since 1.0.0
* @version 2.0.0
*
* @alpha - 早期预览版
* @beta - 功能完整但可能会变更
* @public - 稳定API
* @internal - 不对外公开使用
* @readonly - 不可修改
* @virtual - 可被重写
* @override - 重写父类方法
* @sealed - 不可被继承
*
* @defaultValue 默认值
* @eventProperty - 用于事件属性
*/Best Practices
最佳实践
- Document public API: All exports need docs
- Use examples: Show real usage
- Describe parameters: Clear, concise descriptions
- Document errors: What can be thrown
- Link related items: Use @see tags
- Keep updated: Sync docs with code
- Generate HTML: TypeDoc for browsable docs
- Validate in CI: Check for missing docs
- 公开API必须文档化:所有导出的内容都需要编写文档
- 使用示例代码:展示实际使用场景
- 清晰描述参数:简洁明了的描述
- 文档化错误信息:说明可能抛出的错误
- 关联相关内容:使用@see标签
- 保持文档更新:文档与代码同步
- 生成HTML文档:使用TypeDoc生成可浏览的文档
- 在CI中验证:检查缺失的文档
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
每个已文档化的代码库都应包含:
- 所有公开函数已文档化
- 所有接口和类型已文档化
- 所有参数已描述
- 返回值已文档化
- 复杂函数包含示例代码
- 抛出的错误已文档化
- TypeDoc配置文件
- 生成的文档
- CI流程中集成文档检查
- 包含API概览的README文档