Make writing a habit together! This is the 12th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Hi, I’m Banxia 👴, a sand sculptor who has just started writing. If you like my article, you can follow ➕ like 👍 plus my wechat: FrontendPicker, learn to exchange frontend, become a better engineer ~ follow the public number: do frontend of The Banxia, learn more frontend knowledge! Click me to explore a new world!

As a weakly typed language, JavaScript cannot determine the type of a variable until the program is run. I often write and I don’t know the type of variable. Before TS, I used it all the timeJSDocTo indicate the type of a variable, which is also used by many open source libraries!

JSDoc is an API document generator for JavaScript, similar to Javadoc or phpDocumentor. Adding document comments directly to the source code The JSDoc tool scans the source code and generates an HTML document web site for you.

NPM install JSDoc -g, JSDoc **.js, JSDoc **.js.

Basic usage

The simplest way to use it is to mark the type of a variable

/**
 * @type {string}
 */
let user;
Copy the code

JSDoc also supports tag function methods.

For example, in the *.js file, there is the following function.

function getLength(input){
   return input.
}
Copy the code

As a programmer, I thought it was a string, but the editor didn’t know it and didn’t tell me.

When we add JSDoc comments to it. The editor uses VSCode and supports JSDoc by default. Other editors don’t know!

/ / function getLength(input){return input.}Copy the code

VSCode will give us good code hints.

Better yet, when you call getLength, you forget the number of arguments and their types. Hover the mouse over the function name and VSCode will give you a detailed hint.

Complex parameter type

In addition to the basic types in JS, JSDoc can also define complex types such as objects and arrays. Use @typedef and @property to define a type and then use it elsewhere.

The joint type

Union Types indicate that the value can be one of many Types. This is also supported by TS.

Define a NumberOrString type using @typedef

/**
 * @typedef {(number|string)} NumberOrString
 */
Copy the code

Then it can be used elsewhere.

/**
 * @param {NumberOrString} _x 
 */
 function fn(_x) {
}
Copy the code

object

Use @typedef to define names and @property for attributes

/ * * *@typedef {Object} User
 * @property {string} name
 * @property {number} age* /

Copy the code
/ * * *@param {User}  user* /
 function fn(user) {


Copy the code

The return value

In the function we showed you how to mark the types of parameters, and JSDoc also supports the types of return values.

/**
 * @return {number}
 */
 function fn() {
}

Copy the code