tsdoc-comments
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUse TSDoc for API Comments
使用TSDoc编写API注释
Overview
概述
TSDoc is the standard for documenting TypeScript code. It extends JSDoc with TypeScript-specific features like generic type parameters (). Good documentation explains not just what code does, but why, and helps users understand your API through IDE tooltips and generated docs.
@templateWell-documented code reduces support burden and improves developer experience for your API consumers.
TSDoc是TypeScript代码文档的标准规范。它在JSDoc的基础上扩展了TypeScript专属特性,比如泛型类型参数()。优质的文档不仅要说明代码的功能,还要解释设计意图,并且能通过IDE提示和生成的文档帮助用户理解你的API。
@template编写完善的文档可以减少支持负担,提升API使用者的开发体验。
When to Use This Skill
适用场景
- Documenting public APIs
- Writing library code for others
- Explaining complex type parameters
- Generating documentation from code
- Providing IDE tooltips
- 编写公共API文档
- 为他人编写库代码
- 解释复杂的类型参数
- 从代码中生成文档
- 提供IDE提示
The Iron Rule
铁则
Document public APIs with TSDoc. Explain what, why, and provide examples. Use @template for generic type parameters.
使用TSDoc编写公共API文档。要说明功能、设计意图并提供示例。为泛型类型参数使用标签。
@templateDetection
问题检测
Watch for undocumented public APIs:
typescript
// RED FLAGS - Missing documentation
export function process(data: unknown): Result; // What does it do?
export type Transform<T> = /* complex type */; // What's T for?
export class ApiClient { // How do I use this?
constructor(config: Config) {}
}留意未编写文档的公共API:
typescript
// RED FLAGS - Missing documentation
export function process(data: unknown): Result; // What does it do?
export type Transform<T> = /* complex type */; // What's T for?
export class ApiClient { // How do I use this?
constructor(config: Config) {}
}Basic TSDoc Structure
TSDoc基础结构
typescript
/**
* Short description of what this does.
*
* Longer explanation if needed. Explain why this exists,
* when to use it, and any important caveats.
*
* @param paramName - Description of parameter
* @returns Description of return value
* @example
* ```typescript
* const result = myFunction('input');
* console.log(result); // 'processed: input'
* ```
*/
function myFunction(input: string): string {
return `processed: ${input}`;
}typescript
/**
* Short description of what this does.
*
* Longer explanation if needed. Explain why this exists,
* when to use it, and any important caveats.
*
* @param paramName - Description of parameter
* @returns Description of return value
* @example
* ```typescript
* const result = myFunction('input');
* console.log(result); // 'processed: input'
* ```
*/
function myFunction(input: string): string {
return `processed: ${input}`;
}Documenting Functions
函数文档编写
typescript
/**
* Fetches user data from the API.
*
* Automatically handles authentication and retries failed requests
* up to 3 times with exponential backoff.
*
* @param userId - The unique identifier for the user
* @param options - Optional configuration for the request
* @returns A promise that resolves to the user data
* @throws {ApiError} When the user is not found or the request fails
* @example
* ```typescript
* const user = await fetchUser('123');
* console.log(user.name);
* ```
*/
async function fetchUser(
userId: string,
options?: FetchOptions
): Promise<User> {
// Implementation
}typescript
/**
* Fetches user data from the API.
*
* Automatically handles authentication and retries failed requests
* up to 3 times with exponential backoff.
*
* @param userId - The unique identifier for the user
* @param options - Optional configuration for the request
* @returns A promise that resolves to the user data
* @throws {ApiError} When the user is not found or the request fails
* @example
* ```typescript
* const user = await fetchUser('123');
* console.log(user.name);
* ```
*/
async function fetchUser(
userId: string,
options?: FetchOptions
): Promise<User> {
// Implementation
}Documenting Generic Types
泛型类型文档编写
typescript
/**
* Creates a partial version of a type where all properties are optional.
*
* @template T - The type to make partial
* @example
* ```typescript
* interface User {
* name: string;
* age: number;
* }
*
* type PartialUser = Partial<User>;
* // { name?: string; age?: number; }
* ```
*/
type MyPartial<T> = {
[K in keyof T]?: T[K];
};typescript
/**
* Creates a partial version of a type where all properties are optional.
*
* @template T - The type to make partial
* @example
* ```typescript
* interface User {
* name: string;
* age: number;
* }
*
* type PartialUser = Partial<User>;
* // { name?: string; age?: number; }
* ```
*/
type MyPartial<T> = {
[K in keyof T]?: T[K];
};Documenting Classes
类文档编写
typescript
/**
* Client for interacting with the REST API.
*
* Handles authentication, request retries, and response parsing.
* Create one instance per application and reuse it.
*
* @example
* ```typescript
* const client = new ApiClient({
* baseUrl: 'https://api.example.com',
* apiKey: process.env.API_KEY
* });
*
* const users = await client.users.list();
* ```
*/
export class ApiClient {
/**
* Creates a new API client instance.
*
* @param config - Configuration options for the client
*/
constructor(config: ClientConfig) {}
/**
* Resources for managing users.
*/
readonly users: UserResource;
}typescript
/**
* Client for interacting with the REST API.
*
* Handles authentication, request retries, and response parsing.
* Create one instance per application and reuse it.
*
* @example
* ```typescript
* const client = new ApiClient({
* baseUrl: 'https://api.example.com',
* apiKey: process.env.API_KEY
* });
*
* const users = await client.users.list();
* ```
*/
export class ApiClient {
/**
* Creates a new API client instance.
*
* @param config - Configuration options for the client
*/
constructor(config: ClientConfig) {}
/**
* Resources for managing users.
*/
readonly users: UserResource;
}Common TSDoc Tags
常用TSDoc标签
typescript
/**
* Description of the function.
*
* @param name - Parameter description
* @returns Return value description
* @throws {ErrorType} When/why this error is thrown
* @example Code example showing usage
* @deprecated Use newFunction instead. Will be removed in v2.0.
* @see Related function or documentation
* @internal For internal use only, not part of public API
*/
// For generic types:
/**
* @template T - Description of type parameter
* @template K - Description of second parameter
*/
// For class members:
/**
* @readonly This property is read-only
* @protected This member is protected
*/typescript
/**
* Description of the function.
*
* @param name - Parameter description
* @returns Return value description
* @throws {ErrorType} When/why this error is thrown
* @example Code example showing usage
* @deprecated Use newFunction instead. Will be removed in v2.0.
* @see Related function or documentation
* @internal For internal use only, not part of public API
*/
// For generic types:
/**
* @template T - Description of type parameter
* @template K - Description of second parameter
*/
// For class members:
/**
* @readonly This property is read-only
* @protected This member is protected
*/Pressure Resistance Protocol
规范执行步骤
When documenting code:
- Document public APIs: Everything exported should be documented
- Explain why, not just what: Help users make good decisions
- Provide examples: Show real usage patterns
- Document exceptions: What can go wrong and why
- Keep it current: Update docs when code changes
编写文档时,请遵循以下步骤:
- 为公共API编写文档:所有导出的内容都需要添加文档
- 解释设计意图而非仅功能:帮助用户做出合理的使用决策
- 提供示例:展示实际的使用场景
- 说明异常情况:可能出现的问题及原因
- 保持文档更新:代码变更时同步更新文档
Red Flags
常见问题
| Anti-Pattern | Problem | Solution |
|---|---|---|
| No documentation | Users guess at usage | Add TSDoc comments |
| "Obvious" comments | | Explain why, not what |
| Outdated docs | Misleading users | Update with code changes |
| Missing @template | Generics unexplained | Document type parameters |
| 反模式 | 问题 | 解决方案 |
|---|---|---|
| 无文档 | 用户只能猜测用法 | 添加TSDoc注释 |
| “显而易见”的注释 | | 解释设计意图而非功能 |
| 过时的文档 | 误导用户 | 随代码变更同步更新文档 |
| 缺少@template标签 | 泛型参数用途不明 | 为类型参数添加文档 |
Common Rationalizations
常见借口及纠正
"The code is self-documenting"
“代码本身就是最好的文档”
Reality: Code shows what happens, not why. Documentation explains intent and context.
实际情况:代码只能展示执行逻辑,无法体现设计意图。文档用于解释设计初衷和上下文背景。
"I'll document it later"
“我之后再补文档”
Reality: You won't. Document as you write when context is fresh.
实际情况:你大概率不会补。在编写代码时就添加文档,此时对上下文的理解最清晰。
"It's just internal code"
“这只是内部代码”
Reality: Your future self and coworkers are also users. Document anything non-obvious.
实际情况:未来的你和同事也是使用者。任何非显而易见的代码都需要添加文档。
Quick Reference
快速参考
| Tag | Use For |
|---|---|
| Function parameters |
| Return value description |
| Generic type parameters |
| Usage examples |
| Exceptions thrown |
| Mark deprecated APIs |
| Related documentation |
| 标签 | 用途 |
|---|---|
| 函数参数说明 |
| 返回值说明 |
| 泛型类型参数说明 |
| 使用示例 |
| 抛出的异常说明 |
| 标记已废弃的API |
| 关联文档或函数 |
The Bottom Line
核心要点
Document public APIs with TSDoc. Explain what functions do, why they exist, and how to use them. Good documentation appears in IDE tooltips and reduces support burden.
使用TSDoc编写公共API文档。说明函数的功能、设计意图以及使用方法。优质的文档会在IDE中显示提示,减少支持负担。
Reference
参考资料
- Effective TypeScript, 2nd Edition by Dan Vanderkam
- Item 68: Use TSDoc for API Comments
- 《Effective TypeScript(第2版)》作者:Dan Vanderkam
- 第68条:使用TSDoc编写API注释