Search code examples
javascripttypesjsdoc

JSDoc Mark something as Class after instantiation and define constructor properties


I have mongoose create a Model(class) for me, and I would like to have the class to have intellisense. The problem is I don't know how to mark something as a class, and how to type the constructor for that class.

Looking at JSDocs' docs they only specify how to type a class at the declaration, not when it already has been instantiated. The @class and @constructor tags don't seem to do anything.

Right now I am getting my intellisense by marking it as a function (which it is under the hood, but it would still be great to have the correct colors in VSC) and defining the params:

/**
 * @typedef QPE_Opts
 * @type {object}
 * @prop {string} id - Id of the user 
 * ...
 */
/**
 * @type {function(QPE_Opts) : mongoose.Model<mongoose.Document, {}> }}
 */
const Queue_PoolEntry = mongoose.model('Queue_PoolEntry', Queue_PoolEntrySchema);

Solution

The solution (Was looking at the JsDocs' Documentation which was not providing enough info, thanks @Graham P Heath for giving the better docs) :

/**
 * @type {function(new:mongoose.Model<mongoose.Document, {}>, QPE_Opts ) }}
 */

Solution

  • If you are sure of the type of an object you can type cast it:

    const Queue_PoolEntry = /** @type {QPE_Opts} */ (mongoose.model('Queue_PoolEntry', 
        Queue_PoolEntrySchema));
    

    In situations where you can't actually be sure of the returned type casting may be a code smell. In that case: use code to determine the validity of your type assertion by checking the object for expected properties, and only then casting it.

    let Queue_PoolEntry = mongoose.model('Queue_PoolEntry', 
        Queue_PoolEntrySchema);
    if (Queue_PoolEntry && Queue_PoolEntry.id) {
      Queue_PoolEntry = /** @type {QPE_Opts} */ (Queue_PoolEntry)
    } else {
      throw new Error('mongoose.model(\'Queue_PoolEntry\', Queue_PoolEntrySchema)'+
          'returned something other than a QPE_Opts' + Queue_PoolEntry);
    }