Alexander
Alexander

Reputation: 489

How specify type of class (not its instance) in JSDoc

I have classes:

class Model { 
  static get schema() { }   // static property 'schema'
}
class CustomModel_1 extends Model { }
. . .
class CustomModel_N extends Model { }

I want to declare a new function with argument that specified a type of model (not instance of this type):

/**
* @param {Model} ModelType  <== it is a wrong type because it is an instance of Model
*/
function doSomething(ModelType) {
  const schema = ModelType.schema // <== WebStorm emphasizes 'schema'
}

How I can specify it in JSDoc? Expression {Model} is invalid because it specifies the instance of Model.

Upvotes: 12

Views: 4623

Answers (2)

snicker
snicker

Reputation: 41

This currently works out of the box to aid Visual Studio Code (VScode) with Intellisense auto-completions:

/**
 * @param {typeof Model} ModelType
 */

it just works without any further configuration.

@Darren's answer above is somewhat misleading, it says that jsdoc-typeof-plugin "was the solution that finally worked for me in VSCode", but one doesn't need that plugin on VSCode at all.

Upvotes: 3

Darren
Darren

Reputation: 2034

You may wish to try this:

/**
 * @param {Model.constructor} ModelType
 */
function doSomething(ModelType) {
  // ...
}

That is, you can refer to the constructor function of an object (essentially the class) through its constructor property, which is a built-in property of any JavaScript object.

Depending on your environment, you may also want to try the following:

/**
 * @param {typeof Model} ModelType
 */

This type expression is supported by the Closure Compiler used by JSDoc, although personally I didn't use this since part of my toolchain didn't support this particular syntax.

Also see this JSDoc Typeof Plugin, which was the solution that finally worked for me in VSCode.

Upvotes: 9

Related Questions