JavaScript是一种动态类型语言,它不提供内置的类型检查。这可能会导致代码库的混乱,特别是在团队工作时。
JSDoc --一个强大的工具,用于记录代码、提供类型安全并改进协作。
本指南将深入探讨JSDoc,以及如何在JavaScript和TypeScript项目中有效地使用它。
什么是JSDoc?🤔
JSDoc是一种文档标准,它允许开发人员向其JavaScript代码添加注释。这些注释描述代码功能、定义参数类型、返回值等。
像VS Code这样的工具使用这些注释进行类型提示。
设置JSDoc脚本⚓
开始使用JSDoc,如果您只是将其用于文档和输入提示,则不需要任何特殊的安装。
但是,如果您想生成HTML文档,则需要JSDoc CLI。
安装JSDoc:
npm install -g jsdoc
生成文档:
jsdoc yourFile.js -d docs
此命令在docs的文件夹中生成文档。
编写JSDoc注释📝
/**
* Adds two numbers together.
* @param {number} a - The first number.
* @param {number} b - The second number.
* @returns {number} The sum of the two numbers.
*/
function add(a, b) {
return a + b;
}
常用的JSDoc标签💯
@param:描述一个函数参数
/**
* @param {string} name - The name of the user.
*/
function greet(name) {
console.log(`Hello, ${name}!`);
}
@returns:指定函数的返回类型。
/**
* @returns {boolean} Whether the operation was successful.
*/
function isOperationSuccessful() {
return true;
}
@type:用于变量类型注释。
/** @type {string} */
let username = "JohnDoe";
@typedef和@property:定义自定义类型。
/**
* @typedef {Object} User
* @property {string} name - The name of the user.
* @property {number} age - The age of the user.
*/
/** @type {User} */
const user = { name: "Alice", age: 25 };
@example:提供用法示例。
/**
* Calculates the area of a rectangle.
* @param {number} width - The width of the rectangle.
* @param {number} height - The height of the rectangle.
* @returns {number} The area of the rectangle.
* @example
* const area = calculateArea(5, 10);
* console.log(area); // 50
*/
function calculateArea(width, height) {
return width * height;
}
TypeScript中的JSDoc🔻
虽然TypeScript已经提供了静态类型检查,但仍然可以使用JSDoc来生成文档。
TypeScript原生支持JSDoc。
/**
* Divides two numbers.
* @param {number} numerator - The numerator.
* @param {number} denominator - The denominator.
* @returns {number} The result of the division.
*/
function divide(numerator, denominator) {
if (denominator === 0) {
throw new Error("Cannot divide by zero.");
}
return numerator / denominator;
}
使用JSDoc的好处✅
- 提高可读性: 结构化的注释使你的代码不言自明。
- 类型安全: 像VS Code这样的工具提供类型提示。
- 文档生成: 轻松为您的代码库生成HTML文档。