JSDocリファレンス

以下は、JavaScriptファイルでJSDocアノテーションを使用して型情報を提供する場合に現在サポートされている構造の概要です。

以下に明示的にリストされていないタグ(@asyncなど)は、まだサポートされていませんのでご注意ください。

クラス

ドキュメント

ドキュメンテーションタグは、TypeScriptとJavaScriptの両方で機能します。

その他

意味は通常、jsdoc.appで示されているタグの意味と同じか、そのスーパーセットです。以下のコードは、違いを説明し、各タグの使用例を示します。

注: プレイグラウンドを使用してJSDocサポートを調べることができます

@type

“@type”タグで型を参照できます。型は以下のいずれかになります。

  1. stringnumberのようなプリミティブ。
  2. グローバルまたはインポートされたTypeScript宣言で宣言されている。
  3. JSDocの@typedefタグで宣言されている。

stringのような最も基本的なものから、条件型のような最も高度なものまで、ほとんどのJSDoc型構文とTypeScript構文を使用できます。

js
/**
* @type {string}
*/
var s;
 
/** @type {Window} */
var win;
 
/** @type {PromiseLike<string>} */
var promisedString;
 
// You can specify an HTML Element with DOM properties
/** @type {HTMLElement} */
var myElement = document.querySelector(selector);
element.dataset.myData = "";
Try

@typeは、共用体型を指定できます。たとえば、文字列またはブール値のどちらかであるものを指定できます。

js
/**
* @type {string | boolean}
*/
var sb;
Try

さまざまな構文を使用して配列型を指定できます

js
/** @type {number[]} */
var ns;
/** @type {Array.<number>} */
var jsdoc;
/** @type {Array<number>} */
var nas;
Try

オブジェクトリテラル型を指定することもできます。たとえば、プロパティ 'a'(文字列)と 'b'(数値)を持つオブジェクトは、次の構文を使用します

js
/** @type {{ a: string, b: number }} */
var var9;
Try

標準のJSDoc構文またはTypeScript構文を使用して、文字列および数値インデックスシグネチャを使用して、マップのようなオブジェクトおよび配列のようなオブジェクトを指定できます。

js
/**
* A map-like object that maps arbitrary `string` properties to `number`s.
*
* @type {Object.<string, number>}
*/
var stringToNumber;
 
/** @type {Object.<number, object>} */
var arrayLike;
Try

上記の2つの型は、TypeScriptの型{ [x: string]: number }および{ [x: number]: any }と同等です。コンパイラは両方の構文を理解します。

TypeScriptまたはGoogle Closure構文を使用して関数型を指定できます

js
/** @type {function(string, boolean): number} Closure syntax */
var sbn;
/** @type {(s: string, b: boolean) => number} TypeScript syntax */
var sbn2;
Try

または、指定されていないFunction型を使用することもできます

js
/** @type {Function} */
var fn7;
/** @type {function} */
var fn6;
Try

Closure の他の型も使用できます。

js
/**
* @type {*} - can be 'any' type
*/
var star;
/**
* @type {?} - unknown type (same as 'any')
*/
var question;
Try

キャスト

TypeScript は Google Closure からキャスト構文を借用しています。これにより、括弧で囲まれた式の前に @type タグを追加することで、型を別の型にキャストできます。

js
/**
* @type {number | string}
*/
var numberOrString = Math.random() < 0.5 ? "hello" : 100;
var typeAssertedNumber = /** @type {number} */ (numberOrString);
Try

TypeScript と同様に、const にキャストすることもできます。

js
let one = /** @type {const} */(1);
Try

型のインポート

import types を使用して、他のファイルから宣言をインポートできます。この構文は TypeScript 固有であり、JSDoc 標準とは異なります。

js
// @filename: types.d.ts
export type Pet = {
name: string,
};
 
// @filename: main.js
/**
* @param {import("./types").Pet} p
*/
function walk(p) {
console.log(`Walking ${p.name}...`);
}
Try

import types は、型エイリアス宣言で使用できます。

js
/**
* @typedef {import("./types").Pet} Pet
*/
 
/**
* @type {Pet}
*/
var myPet;
myPet.name;
Try

import types を使用して、型が不明な場合や、型付けが面倒な大きな型の場合に、モジュールから値の型を取得できます。

js
/**
* @type {typeof import("./accounts").userAccount}
*/
var x = require("./accounts").userAccount;
Try

@param および @returns

@param@type と同じ型構文を使用しますが、パラメータ名が追加されます。パラメータ名は、角括弧で囲むことでオプションとして宣言することもできます。

js
// Parameters may be declared in a variety of syntactic forms
/**
* @param {string} p1 - A string param.
* @param {string=} p2 - An optional param (Google Closure syntax)
* @param {string} [p3] - Another optional param (JSDoc syntax).
* @param {string} [p4="test"] - An optional param with a default value
* @returns {string} This is the result
*/
function stringsStringStrings(p1, p2, p3, p4) {
// TODO
}
Try

同様に、関数の戻り値の型についても同様です。

js
/**
* @return {PromiseLike<string>}
*/
function ps() {}
 
/**
* @returns {{ a: string, b: number }} - May use '@returns' as well as '@return'
*/
function ab() {}
Try

@typedef@callback、および @param

@typedef を使用して複合型を定義できます。同様の構文が @param でも機能します。

js
/**
* @typedef {Object} SpecialType - creates a new type named 'SpecialType'
* @property {string} prop1 - a string property of SpecialType
* @property {number} prop2 - a number property of SpecialType
* @property {number=} prop3 - an optional number property of SpecialType
* @prop {number} [prop4] - an optional number property of SpecialType
* @prop {number} [prop5=42] - an optional number property of SpecialType with default
*/
 
/** @type {SpecialType} */
var specialTypeObject;
specialTypeObject.prop3;
Try

最初の行では object または Object のいずれかを使用できます。

js
/**
* @typedef {object} SpecialType1 - creates a new type named 'SpecialType1'
* @property {string} prop1 - a string property of SpecialType1
* @property {number} prop2 - a number property of SpecialType1
* @property {number=} prop3 - an optional number property of SpecialType1
*/
 
/** @type {SpecialType1} */
var specialTypeObject1;
Try

@param は、1 回限りの型指定に同様の構文を許可します。ネストされたプロパティ名は、パラメータの名前でプレフィックスを付ける必要があることに注意してください。

js
/**
* @param {Object} options - The shape is the same as SpecialType above
* @param {string} options.prop1
* @param {number} options.prop2
* @param {number=} options.prop3
* @param {number} [options.prop4]
* @param {number} [options.prop5=42]
*/
function special(options) {
return (options.prop4 || 1001) + options.prop5;
}
Try

@callback@typedef に似ていますが、オブジェクト型ではなく関数型を指定します。

js
/**
* @callback Predicate
* @param {string} data
* @param {number} [index]
* @returns {boolean}
*/
 
/** @type {Predicate} */
const ok = (s) => !(s.length % 2);
Try

もちろん、これらの型は、1 行の @typedef で TypeScript 構文を使用して宣言できます。

js
/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType */
/** @typedef {(data: string, index?: number) => boolean} Predicate */

@template

@template タグを使用して、型パラメータを宣言できます。これにより、ジェネリックな関数、クラス、または型を作成できます。

js
/**
* @template T
* @param {T} x - A generic parameter that flows through to the return type
* @returns {T}
*/
function id(x) {
return x;
}
 
const a = id("string");
const b = id(123);
const c = id({});
Try

カンマまたは複数のタグを使用して、複数の型パラメータを宣言します。

js
/**
* @template T,U,V
* @template W,X
*/

また、型パラメータ名の前に型制約を指定することもできます。リストの最初の型パラメータのみが制約されます。

js
/**
* @template {string} K - K must be a string or string literal
* @template {{ serious(): string }} Seriousalizable - must have a serious method
* @param {K} key
* @param {Seriousalizable} object
*/
function seriousalize(key, object) {
// ????
}
Try

最後に、型パラメータのデフォルトを指定できます。

js
/** @template [T=object] */
class Cache {
/** @param {T} initial */
constructor(initial) {
}
}
let c = new Cache()
Try

@satisfies

@satisfies は、TypeScript の後置 演算子 satisfies へのアクセスを提供します。Satisfies は、値が型を実装していることを宣言するために使用されますが、値の型には影響しません。

js
// @ts-check
/**
* @typedef {"hello world" | "Hello, world"} WelcomeMessage
*/
 
/** @satisfies {WelcomeMessage} */
const message = "hello world"
const message: "hello world"
 
/** @satisfies {WelcomeMessage} */
Type '"Hello world!"' does not satisfy the expected type 'WelcomeMessage'.1360Type '"Hello world!"' does not satisfy the expected type 'WelcomeMessage'.
const failingMessage = "Hello world!"
 
/** @type {WelcomeMessage} */
const messageUsingType = "hello world"
const messageUsingType: WelcomeMessage
Try

クラス

クラスは ES6 クラスとして宣言できます。

js
class C {
/**
* @param {number} data
*/
constructor(data) {
// property types can be inferred
this.name = "foo";
 
// or set explicitly
/** @type {string | null} */
this.title = null;
 
// or simply annotated, if they're set elsewhere
/** @type {number} */
this.size;
 
this.initialize(data); // Should error, initializer expects a string
}
/**
* @param {string} s
*/
initialize = function (s) {
this.size = s.length;
};
}
 
var c = new C(0);
 
// C should only be called with new, but
// because it is JavaScript, this is allowed and
// considered an 'any'.
var result = C(1);
Try

また、コンストラクター関数として宣言することもできます。この場合は、@constructor@this とともに使用します。

プロパティ修飾子

@public@private、および @protected は、TypeScript の publicprivate、および protected とまったく同様に機能します。

js
// @ts-check
 
class Car {
constructor() {
/** @private */
this.identifier = 100;
}
 
printIdentifier() {
console.log(this.identifier);
}
}
 
const c = new Car();
console.log(c.identifier);
Property 'identifier' is private and only accessible within class 'Car'.2341Property 'identifier' is private and only accessible within class 'Car'.
Try
  • @public は常に暗黙的に指定されており、省略できますが、プロパティがどこからでもアクセスできることを意味します。
  • @private は、プロパティが包含クラス内でのみ使用できることを意味します。
  • @protected は、プロパティが包含クラス内、およびすべての派生サブクラス内でのみ使用でき、包含クラスの異なるインスタンスでは使用できないことを意味します。

@public@private、および @protected は、コンストラクター関数では機能しません。

@readonly

@readonly 修飾子は、プロパティが初期化中にのみ書き込まれることを保証します。

js
// @ts-check
 
class Car {
constructor() {
/** @readonly */
this.identifier = 100;
}
 
printIdentifier() {
console.log(this.identifier);
}
}
 
const c = new Car();
console.log(c.identifier);
Try

@override

@override は TypeScript と同じように機能します。基底クラスのメソッドをオーバーライドするメソッドで使用します。

js
export class C {
m() { }
}
class D extends C {
/** @override */
m() { }
}
Try

オーバーライドをチェックするには、tsconfig で noImplicitOverride: true を設定します。

@extends

JavaScript クラスがジェネリック基底クラスを拡張する場合、型引数を渡すための JavaScript 構文はありません。@extends タグを使用すると、これが可能になります。

js
/**
* @template T
* @extends {Set<T>}
*/
class SortableSet extends Set {
// ...
}
Try

@extends はクラスでのみ機能することに注意してください。現在、コンストラクター関数がクラスを拡張する方法はありません。

@implements

同様に、TypeScript インターフェイスを実装するための JavaScript 構文はありません。@implements タグは TypeScript と同じように機能します。

js
/** @implements {Print} */
class TextBook {
print() {
// TODO
}
}
Try

@constructor

コンパイラーは、this-property の割り当てに基づいてコンストラクター関数を推論しますが、@constructor タグを追加すると、チェックをより厳密にし、提案を改善できます。

js
/**
* @constructor
* @param {number} data
*/
function C(data) {
// property types can be inferred
this.name = "foo";
 
// or set explicitly
/** @type {string | null} */
this.title = null;
 
// or simply annotated, if they're set elsewhere
/** @type {number} */
this.size;
 
this.initialize(data);
Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.
}
/**
* @param {string} s
*/
C.prototype.initialize = function (s) {
this.size = s.length;
};
 
var c = new C(0);
c.size;
 
var result = C(1);
Value of type 'typeof C' is not callable. Did you mean to include 'new'?2348Value of type 'typeof C' is not callable. Did you mean to include 'new'?
Try

注: エラーメッセージは、JSConfigcheckJs が有効になっている JS コードベースでのみ表示されます。

@constructor を使用すると、コンストラクター関数 C 内で this がチェックされるため、initialize メソッドの提案が表示され、数値が渡された場合はエラーが表示されます。エディターでは、C を構築せずに呼び出した場合に警告が表示されることもあります。

残念ながら、これは、呼び出し可能でもあるコンストラクター関数では @constructor を使用できないことを意味します。

@this

コンパイラーは、通常、操作するコンテキストがある場合に this の型を理解できます。そうでない場合は、@thisthis の型を明示的に指定できます。

js
/**
* @this {HTMLElement}
* @param {*} e
*/
function callbackForLater(e) {
this.clientHeight = parseInt(e); // should be fine!
}
Try

ドキュメント

@deprecated

関数、メソッド、またはプロパティが非推奨になった場合、/** @deprecated */ JSDoc コメントでマークすることで、ユーザーに知らせることができます。その情報は、補完リストや、エディターが特別に処理できる提案診断として表示されます。VS Code のようなエディターでは、非推奨の値は通常、このように取り消し線付きで表示されます。

js
/** @deprecated */
const apiV1 = {};
const apiV2 = {};
 
apiV;
   
 
 
Try

@see

@see を使用すると、プログラム内の他の名前にリンクできます。

ts
type Box<T> = { t: T }
/** @see Box for implementation details */
type Boxify<T> = { [K in keyof T]: Box<T> };
Try

一部のエディターでは、Box をリンクに変換して、そこへのジャンプと戻りを容易にします。

@link@see に似ていますが、他のタグ内で使用できる点が異なります。

ts
type Box<T> = { t: T }
/** @returns A {@link Box} containing the parameter. */
function box<U>(u: U): Box<U> {
return { t: u };
}
Try

その他

@enum

@enum タグを使用すると、メンバーがすべて指定された型であるオブジェクトリテラルを作成できます。JavaScript のほとんどのオブジェクトリテラルとは異なり、他のメンバーは許可しません。@enum は、Google Closure の @enum タグとの互換性を目的としています。

js
/** @enum {number} */
const JSDocState = {
BeginningOfLine: 0,
SawAsterisk: 1,
SavingComments: 2,
};
 
JSDocState.SawAsterisk;
Try

@enum は TypeScript の enum とは大きく異なり、はるかに単純であることに注意してください。ただし、TypeScript の enum とは異なり、@enum は任意の型を持つことができます。

js
/** @enum {function(number): number} */
const MathFuncs = {
add1: (n) => n + 1,
id: (n) => -n,
sub1: (n) => n - 1,
};
 
MathFuncs.add1;
Try

@author

@author を使用して、項目の作成者を指定できます。

ts
/**
* Welcome to awesome.ts
* @author Ian Awesome <i.am.awesome@example.com>
*/
Try

メールアドレスを山かっこで囲むことを忘れないでください。そうしないと、@example が新しいタグとして解析されます。

その他のサポートされているパターン

js
var someObj = {
/**
* @param {string} param1 - JSDocs on property assignments work
*/
x: function (param1) {},
};
 
/**
* As do jsdocs on variable assignments
* @return {Window}
*/
let someFunc = function () {};
 
/**
* And class methods
* @param {string} greeting The greeting to use
*/
Foo.prototype.sayHi = (greeting) => console.log("Hi!");
 
/**
* And arrow function expressions
* @param {number} x - A multiplier
*/
let myArrow = (x) => x * x;
 
/**
* Which means it works for function components in JSX too
* @param {{a: string, b: number}} props - Some param
*/
var fc = (props) => <div>{props.a.charAt(0)}</div>;
 
/**
* A parameter can be a class constructor, using Google Closure syntax.
*
* @param {{new(...args: any[]): object}} C - The class to register
*/
function registerClass(C) {}
 
/**
* @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any')
*/
function fn10(p1) {}
 
/**
* @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any')
*/
function fn9(p1) {
return p1.join();
}
Try

サポートされていないパターン

オブジェクトリテラル型におけるプロパティ型に対する後置の等号は、オプションのプロパティを指定しません。

js
/**
* @type {{ a: string, b: number= }}
*/
var wrong;
/**
* Use postfix question on the property name instead:
* @type {{ a: string, b?: number }}
*/
var right;
Try

Nullable 型は、strictNullChecks がオンの場合のみ意味を持ちます。

js
/**
* @type {?number}
* With strictNullChecks: true -- number | null
* With strictNullChecks: false -- number
*/
var nullable;
Try

TypeScript ネイティブの構文は、共用体型です。

js
/**
* @type {number | null}
* With strictNullChecks: true -- number | null
* With strictNullChecks: false -- number
*/
var unionNullable;
Try

非 nullable 型は意味がなく、元の型と同じように扱われます。

js
/**
* @type {!number}
* Just has type number
*/
var normal;
Try

JSDoc の型システムとは異なり、TypeScript では、型に null が含まれるか否かのみをマークできます。明示的な非 null 値は存在しません。strictNullChecks がオンの場合、number は nullable ではありません。オフの場合、number は nullable です。

サポートされていないタグ

TypeScript は、サポートされていない JSDoc タグをすべて無視します。

次のタグは、サポートするためのオープンな課題があります。

TypeScript ドキュメントはオープンソースプロジェクトです。これらのページの改善にご協力ください プルリクエストを送信

このページの貢献者
OTOrta Therox (23)
NSNathan Shively-Sanders (6)
RGRohit Gohri (2)
GUGreg Uzelac (1)
D(KDylan (Jeongtae Kim) (1)
6+

最終更新日: 2024年3月21日