以下は、JavaScriptファイルでJSDocアノテーションを使用して型情報を提供する場合に現在サポートされている構造の概要です。
以下に明示的にリストされていないタグ(@async
など)は、まだサポートされていませんのでご注意ください。
型
クラス
- プロパティ修飾子
@public
、@private
、@protected
、@readonly
@override
@extends
(または@augments
)@implements
@class
(または@constructor
)@this
ドキュメント
ドキュメンテーションタグは、TypeScriptとJavaScriptの両方で機能します。
その他
意味は通常、jsdoc.appで示されているタグの意味と同じか、そのスーパーセットです。以下のコードは、違いを説明し、各タグの使用例を示します。
注: プレイグラウンドを使用してJSDocサポートを調べることができます。
型
@type
“@type”タグで型を参照できます。型は以下のいずれかになります。
string
やnumber
のようなプリミティブ。- グローバルまたはインポートされたTypeScript宣言で宣言されている。
- JSDocの
@typedef
タグで宣言されている。
string
のような最も基本的なものから、条件型のような最も高度なものまで、ほとんどのJSDoc型構文とTypeScript構文を使用できます。
jsTry
/*** @type {string}*/vars ;/** @type {Window} */varwin ;/** @type {PromiseLike<string>} */varpromisedString ;// You can specify an HTML Element with DOM properties/** @type {HTMLElement} */varmyElement =document .querySelector (selector );element .dataset .myData = "";
@type
は、共用体型を指定できます。たとえば、文字列またはブール値のどちらかであるものを指定できます。
jsTry
/*** @type {string | boolean}*/varsb ;
さまざまな構文を使用して配列型を指定できます
jsTry
/** @type {number[]} */varns ;/** @type {Array.<number>} */varjsdoc ;/** @type {Array<number>} */varnas ;
オブジェクトリテラル型を指定することもできます。たとえば、プロパティ 'a'(文字列)と 'b'(数値)を持つオブジェクトは、次の構文を使用します
jsTry
/** @type {{ a: string, b: number }} */varvar9 ;
標準のJSDoc構文またはTypeScript構文を使用して、文字列および数値インデックスシグネチャを使用して、マップのようなオブジェクトおよび配列のようなオブジェクトを指定できます。
jsTry
/*** A map-like object that maps arbitrary `string` properties to `number`s.** @type {Object.<string, number>}*/varstringToNumber ;/** @type {Object.<number, object>} */vararrayLike ;
上記の2つの型は、TypeScriptの型{ [x: string]: number }
および{ [x: number]: any }
と同等です。コンパイラは両方の構文を理解します。
TypeScriptまたはGoogle Closure構文を使用して関数型を指定できます
jsTry
/** @type {function(string, boolean): number} Closure syntax */varsbn ;/** @type {(s: string, b: boolean) => number} TypeScript syntax */varsbn2 ;
または、指定されていないFunction
型を使用することもできます
jsTry
/** @type {Function} */varfn7 ;/** @type {function} */varfn6 ;
Closure の他の型も使用できます。
jsTry
/*** @type {*} - can be 'any' type*/varstar ;/*** @type {?} - unknown type (same as 'any')*/varquestion ;
キャスト
TypeScript は Google Closure からキャスト構文を借用しています。これにより、括弧で囲まれた式の前に @type
タグを追加することで、型を別の型にキャストできます。
jsTry
/*** @type {number | string}*/varnumberOrString =Math .random () < 0.5 ? "hello" : 100;vartypeAssertedNumber = /** @type {number} */ (numberOrString );
TypeScript と同様に、const
にキャストすることもできます。
jsTry
letone = /** @type {const} */(1);
型のインポート
import types を使用して、他のファイルから宣言をインポートできます。この構文は TypeScript 固有であり、JSDoc 標準とは異なります。
jsTry
// @filename: types.d.tsexport typePet = {name : string,};// @filename: main.js/*** @param {import("./types").Pet} p*/functionwalk (p ) {console .log (`Walking ${p .name }...`);}
import types は、型エイリアス宣言で使用できます。
jsTry
/*** @typedef {import("./types").Pet} Pet*//*** @type {Pet}*/varmyPet ;myPet .name ;
import types を使用して、型が不明な場合や、型付けが面倒な大きな型の場合に、モジュールから値の型を取得できます。
jsTry
/*** @type {typeof import("./accounts").userAccount}*/varx =require ("./accounts").userAccount ;
@param
および @returns
@param
は @type
と同じ型構文を使用しますが、パラメータ名が追加されます。パラメータ名は、角括弧で囲むことでオプションとして宣言することもできます。
jsTry
// 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*/functionstringsStringStrings (p1 ,p2 ,p3 ,p4 ) {// TODO}
同様に、関数の戻り値の型についても同様です。
jsTry
/*** @return {PromiseLike<string>}*/functionps () {}/*** @returns {{ a: string, b: number }} - May use '@returns' as well as '@return'*/functionab () {}
@typedef
、@callback
、および @param
@typedef
を使用して複合型を定義できます。同様の構文が @param
でも機能します。
jsTry
/*** @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} */varspecialTypeObject ;specialTypeObject .prop3 ;
最初の行では object
または Object
のいずれかを使用できます。
jsTry
/*** @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} */varspecialTypeObject1 ;
@param
は、1 回限りの型指定に同様の構文を許可します。ネストされたプロパティ名は、パラメータの名前でプレフィックスを付ける必要があることに注意してください。
jsTry
/*** @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]*/functionspecial (options ) {return (options .prop4 || 1001) +options .prop5 ;}
@callback
は @typedef
に似ていますが、オブジェクト型ではなく関数型を指定します。
jsTry
/*** @callback Predicate* @param {string} data* @param {number} [index]* @returns {boolean}*//** @type {Predicate} */constok = (s ) => !(s .length % 2);
もちろん、これらの型は、1 行の @typedef
で TypeScript 構文を使用して宣言できます。
js
/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType *//** @typedef {(data: string, index?: number) => boolean} Predicate */
@template
@template
タグを使用して、型パラメータを宣言できます。これにより、ジェネリックな関数、クラス、または型を作成できます。
jsTry
/*** @template T* @param {T} x - A generic parameter that flows through to the return type* @returns {T}*/functionid (x ) {returnx ;}consta =id ("string");constb =id (123);constc =id ({});
カンマまたは複数のタグを使用して、複数の型パラメータを宣言します。
js
/*** @template T,U,V* @template W,X*/
また、型パラメータ名の前に型制約を指定することもできます。リストの最初の型パラメータのみが制約されます。
jsTry
/*** @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*/functionseriousalize (key ,object ) {// ????}
最後に、型パラメータのデフォルトを指定できます。
jsTry
/** @template [T=object] */classCache {/** @param {T} initial */constructor(initial ) {}}letc = newCache ()
@satisfies
@satisfies
は、TypeScript の後置 演算子 satisfies
へのアクセスを提供します。Satisfies は、値が型を実装していることを宣言するために使用されますが、値の型には影響しません。
jsTry
// @ts-check/*** @typedef {"hello world" | "Hello, world"} WelcomeMessage*//** @satisfies {WelcomeMessage} */constmessage = "hello world"/** @satisfies {Type '"Hello world!"' does not satisfy the expected type 'WelcomeMessage'.1360Type '"Hello world!"' does not satisfy the expected type 'WelcomeMessage'.WelcomeMessage } */constfailingMessage = "Hello world!"/** @type {WelcomeMessage} */constmessageUsingType = "hello world"
クラス
クラスは ES6 クラスとして宣言できます。
jsTry
classC {/*** @param {number} data*/constructor(data ) {// property types can be inferredthis.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 ;};}varc = newC (0);// C should only be called with new, but// because it is JavaScript, this is allowed and// considered an 'any'.varresult =C (1);
また、コンストラクター関数として宣言することもできます。この場合は、@constructor
を @this
とともに使用します。
プロパティ修飾子
@public
、@private
、および @protected
は、TypeScript の public
、private
、および protected
とまったく同様に機能します。
jsTry
// @ts-checkclassCar {constructor() {/** @private */this.identifier = 100;}printIdentifier () {console .log (this.identifier );}}constc = newCar ();Property 'identifier' is private and only accessible within class 'Car'.2341Property 'identifier' is private and only accessible within class 'Car'.console .log (c .); identifier
@public
は常に暗黙的に指定されており、省略できますが、プロパティがどこからでもアクセスできることを意味します。@private
は、プロパティが包含クラス内でのみ使用できることを意味します。@protected
は、プロパティが包含クラス内、およびすべての派生サブクラス内でのみ使用でき、包含クラスの異なるインスタンスでは使用できないことを意味します。
@public
、@private
、および @protected
は、コンストラクター関数では機能しません。
@readonly
@readonly
修飾子は、プロパティが初期化中にのみ書き込まれることを保証します。
jsTry
// @ts-checkclassCar {constructor() {/** @readonly */this.identifier = 100;}printIdentifier () {console .log (this.identifier );}}constc = newCar ();console .log (c .identifier );
@override
@override
は TypeScript と同じように機能します。基底クラスのメソッドをオーバーライドするメソッドで使用します。
jsTry
export classC {m () { }}classD extendsC {/** @override */m () { }}
オーバーライドをチェックするには、tsconfig で noImplicitOverride: true
を設定します。
@extends
JavaScript クラスがジェネリック基底クラスを拡張する場合、型引数を渡すための JavaScript 構文はありません。@extends
タグを使用すると、これが可能になります。
jsTry
/*** @template T* @extends {Set<T>}*/classSortableSet extendsSet {// ...}
@extends
はクラスでのみ機能することに注意してください。現在、コンストラクター関数がクラスを拡張する方法はありません。
@implements
同様に、TypeScript インターフェイスを実装するための JavaScript 構文はありません。@implements
タグは TypeScript と同じように機能します。
jsTry
/** @implements {Print} */classTextBook {// TODO}}
@constructor
コンパイラーは、this-property の割り当てに基づいてコンストラクター関数を推論しますが、@constructor
タグを追加すると、チェックをより厳密にし、提案を改善できます。
jsTry
/*** @constructor* @param {number} data*/functionC (data ) {// property types can be inferredthis.name = "foo";// or set explicitly/** @type {string | null} */this.title = null;// or simply annotated, if they're set elsewhere/** @type {number} */this.size ;this.Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.initialize (); data }/*** @param {string} s*/C .prototype .initialize = function (s ) {this.size =s .length ;};varc = newC (0);c .size ;varValue 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'?result =C (1);
注: エラーメッセージは、JSConfig と
checkJs
が有効になっている JS コードベースでのみ表示されます。
@constructor
を使用すると、コンストラクター関数 C
内で this
がチェックされるため、initialize
メソッドの提案が表示され、数値が渡された場合はエラーが表示されます。エディターでは、C
を構築せずに呼び出した場合に警告が表示されることもあります。
残念ながら、これは、呼び出し可能でもあるコンストラクター関数では @constructor
を使用できないことを意味します。
@this
コンパイラーは、通常、操作するコンテキストがある場合に this
の型を理解できます。そうでない場合は、@this
で this
の型を明示的に指定できます。
jsTry
/*** @this {HTMLElement}* @param {*} e*/functioncallbackForLater (e ) {this.clientHeight =parseInt (e ); // should be fine!}
ドキュメント
@deprecated
関数、メソッド、またはプロパティが非推奨になった場合、/** @deprecated */
JSDoc コメントでマークすることで、ユーザーに知らせることができます。その情報は、補完リストや、エディターが特別に処理できる提案診断として表示されます。VS Code のようなエディターでは、非推奨の値は通常、このように取り消し線付きで表示されます。
jsTry
/** @deprecated */constapiV1 = {};constapiV2 = {};apiV ;
@see
@see
を使用すると、プログラム内の他の名前にリンクできます。
tsTry
typeBox <T > = {t :T }/** @see Box for implementation details */typeBoxify <T > = { [K in keyofT ]:Box <T > };
一部のエディターでは、Box
をリンクに変換して、そこへのジャンプと戻りを容易にします。
@link
@link
は @see
に似ていますが、他のタグ内で使用できる点が異なります。
tsTry
typeBox <T > = {t :T }/** @returns A {@link Box} containing the parameter. */functionbox <U >(u :U ):Box <U > {return {t :u };}
その他
@enum
@enum
タグを使用すると、メンバーがすべて指定された型であるオブジェクトリテラルを作成できます。JavaScript のほとんどのオブジェクトリテラルとは異なり、他のメンバーは許可しません。@enum
は、Google Closure の @enum
タグとの互換性を目的としています。
jsTry
/** @enum {number} */constJSDocState = {BeginningOfLine : 0,SawAsterisk : 1,SavingComments : 2,};JSDocState .SawAsterisk ;
@enum
は TypeScript の enum
とは大きく異なり、はるかに単純であることに注意してください。ただし、TypeScript の enum とは異なり、@enum
は任意の型を持つことができます。
jsTry
/** @enum {function(number): number} */constMathFuncs = {add1 : (n ) =>n + 1,id : (n ) => -n ,sub1 : (n ) =>n - 1,};MathFuncs .add1 ;
@author
@author
を使用して、項目の作成者を指定できます。
tsTry
/*** Welcome to awesome.ts* @author Ian Awesome <i.am.awesome@example.com>*/
メールアドレスを山かっこで囲むことを忘れないでください。そうしないと、@example
が新しいタグとして解析されます。
その他のサポートされているパターン
jsTry
varsomeObj = {/*** @param {string} param1 - JSDocs on property assignments work*/x : function (param1 ) {},};/*** As do jsdocs on variable assignments* @return {Window}*/letsomeFunc = 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*/letmyArrow = (x ) =>x *x ;/*** Which means it works for function components in JSX too* @param {{a: string, b: number}} props - Some param*/varfc = (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*/functionregisterClass (C ) {}/*** @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any')*/functionfn10 (p1 ) {}/*** @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any')*/functionfn9 (p1 ) {returnp1 .join ();}
サポートされていないパターン
オブジェクトリテラル型におけるプロパティ型に対する後置の等号は、オプションのプロパティを指定しません。
jsTry
/*** @type {{ a: string, b: number= }}*/varwrong ;/*** Use postfix question on the property name instead:* @type {{ a: string, b?: number }}*/varright ;
Nullable 型は、strictNullChecks
がオンの場合のみ意味を持ちます。
jsTry
/*** @type {?number}* With strictNullChecks: true -- number | null* With strictNullChecks: false -- number*/varnullable ;
TypeScript ネイティブの構文は、共用体型です。
jsTry
/*** @type {number | null}* With strictNullChecks: true -- number | null* With strictNullChecks: false -- number*/varunionNullable ;
非 nullable 型は意味がなく、元の型と同じように扱われます。
jsTry
/*** @type {!number}* Just has type number*/varnormal ;
JSDoc の型システムとは異なり、TypeScript では、型に null が含まれるか否かのみをマークできます。明示的な非 null 値は存在しません。strictNullChecks がオンの場合、number
は nullable ではありません。オフの場合、number
は nullable です。
サポートされていないタグ
TypeScript は、サポートされていない JSDoc タグをすべて無視します。
次のタグは、サポートするためのオープンな課題があります。
@const
(issue #19672)@inheritdoc
(issue #23215)@memberof
(issue #7237)@yields
(issue #23857)