JSDoc은 자바스크립트 소스 코드 파일들에 주해를 달기 위해 사용하는 마크업 언어이다. JSDoc을 포함하는 주석을 사용하는 프로그래머들은 자신들이 작성하는 코드의 API를 설명하는 설명 문서를 추가할 수 있다.
자바스크립트 소스코드에 다음과 같이 @ts-check를 주석으로 추가하면 TypeScript처럼 타입 및 에러 체크가 가능하다.
// @ts-check
function compact(arr) {
if (orr.length > 10)
// 'orr' 이름을 찾을 수 없습니다.ts(2304)
return arr.trim(0, 10);
return arr;
}
변수나 함수 등의 타입 이름을 참조할 수 있다.
/** @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;
// TypeScript syntax를 사용하는 방법
/**
* 두 수의 합을 구한다.
* @type { (a: number, b: number) => number }
*/
const add = (a, b) => a + b;
// Closure syntax를 사용하는 방법
/**
* 두 수의 곱을 구한다.
* @type { function(number, number): number }
*/
const multiply = (a, b) => a * b;
// JSDoc syntax를 사용하는 방법
/**
* 두 수의 차를 구한다.
* @param {number} a - the first thing
* @param {number} b - the second thing
* @returns {number}
*/
const subtract = (a, b) => a - b;
@param은 타입 구문인 @type과 동일하게 사용할 수 있다, 단, @param은 매개변수 이름을 추가할 수 있고 매개변수는 이름을 대괄호로 감싸서 선택적 매개변수임을 명시할 수 있다.
// Parameters may be declared in a variety of syntactic forms
/**
* @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) {
// TODO
}
복잡한 타입을 정의할 때 사용한다.
/**
* 할일
* @typedef {Object} Todo
* @property {number} id - 할일 id
* @property {string} content - 할일 내용
* @property {boolean} completed - 할일 완료 여부
*/
/**
* 할일 목록
* @type {Todo[]}
*/
const todos = [
{ id: 1, content: "HTML", completed: false },
{ id: 2, content: "CSS", completed: true },
{ id: 3, content: "Javascript", completed: false },
];
@callback은 @typedef와 비슷하다. 하지만 이것은 object 타입 대신 특정한 function 타입을 지정한다.
/**
* @callback Predicate
* @param {string} data
* @param {number} [index]
* @returns {boolean}
*/
/** @type {Predicate} */
const ok = (s) => !(s.length % 2);
@template 태그를 사용하여 제네릭 함수를 선언할 수 있다.
/**
* @template T
* @param {T} x - 제네릭 매개변수는 리턴 타입과 같게 됩니다
* @return {T}
*/
function id(x) {
return x;
}
const a = id("string");
const b = id(123);
const c = id({});
컴파일러는 코드가 동작할 컨텍스트가 있다면 보통 this의 타입을 파악할 수 있다. 그렇지 않은 경우, @this를 사용하여 명확하게 this의 타입을 지정할 수 있다.
/**
* @this {HTMLElement}
* @param {*} e
*/
function callbackForLater(e) {
this.clientHeight = parseInt(e); // 잘 작동해야 합니다!
}
Javascript 클래스를 제네릭 기반 클래스로부터 상속(extend)하면, 매개변수가 어떤 타입이 되어야 하는지 지정할 곳이 없다. @extends 태그는 이러한 타입 매개변수를 위한 위치를 제공한다.
/**
* @template T
* @extends {Set<T>}
*/
class SortableSet extends Set {
// ...
}
@enum 태그는 멤버가 모두 지정된 객체 리터럴을 만들 수 있게 도와준다. Javascript 대부분의 객체 리터럴과 달리, 이 태그는 다른 멤버를 허용하지 않는다.
/** @enum {number} */
const JSDocState = {
BeginningOfLine: 0,
SawAsterisk: 1,
SavingComments: 2,
};
JSDocState.SawAsterisk;
문서 설명 주석을 사용할 수 있다.
/**
* @filename 파일이름
* @file 파일에 대한 설명을 제공한다.
* @author boyon <boyon@email.com>
* @description some description
* @version 1.2.3
* @todo Write the documentation.
* @license Apache-2.0
* @summary Summary goes here.
*/