JSDoc은 Javadoc 또는 phpDocumentor와 유사한 javascript용 API 문서 생성기이다. 코드 자체와 함께 소스코드에 직접 문서 주석을 추가한다.
VSCode에서 순수한 자바스크립트 소스코드에 @ts-check 를 주석으로 추가하면 typescript처럼 타입 및 에러 체크가 가능하다.
주석을 사용하여 함수에 대해 설명하거나, @ts-check를 이용하면 설명과 어느정도의 에러 체크가 가능하지만, JSDoc의 태그를 사용하여 더 많은 정보를 제공할 수 있다. 예를 들어 함수가 클래스의 생성자인 경우 아래와 같이 사용할 수 있다.
/** 이 함수는 Book클래스의 생성자이다. */
function Book(title, author) {}
/**
* 책을 의미하는 함수이다.
* @constructor
* @param {string} title - 책의 제목
* @param {string} author - 책의 저자
*/
function Book(title, author) {}
변수 타입
/** @type {string} */
let str;
/** @type {number} */
let num;
/** @type {boolean} */
let bool;
/** @type {*} */
let any;
/** @type {?} */
let unknown;
/** @type {number[]} */
let nums;
/** @type { {id: number, content: string, completed: boolean} } */
let obj;
/** @type {string|number} */
let union;
/** @type {Array<{ id: number, content: string, completed: boolean }>} */
let generic;
함수 타입
/**
* @description TypeScript syntax를 사용하는 방법
* @description 두 수의 합을 구한다.
* @type { (a: number, b: number) => number }
*/
const add = (a, b) => a + b;
/**
* @description Closure syntax를 사용하는 방법
* @description 두 수의 곱을 구한다.
* @type { function(number, number): number }
*/
const multiply = (a, b) => a * b;
/**
* @description JSDoc syntax를 사용하는 방법
* @description 두 수의 차를 구한다.
* @param {number} a - the first thing
* @param {number} b - the second thing
* @returns {number}
*/
const subtract = (a, b) => a - b;
/**
* @param {string} p1 - A string param.
* @param {string=} p2 - An optional param (Closure syntax)
* @param {string} [p3] - Another optional param (JSDoc syntax).
* @param {string} [p4="test"] - An optional param with a default value
* @return {string} This is the result
*/
function stringsStringStrings(p1, p2, p3, p4) {
return p1 + p2 + p3 + p4;
}
@param은 타입 구문인 @type과 동일하게 사용할 수 있다. 단, @param은 매개변수 이름을 추가할 수 있고 매개변수는 이름을 대괄호로 감싸서 선택적 매개변수임을 명시할 수 있다.