Home > Blockchain >  Could JavaScript variables be used as JSDoc types and why do so?
Could JavaScript variables be used as JSDoc types and why do so?

Time:01-08

I'm checking this code and I've encountered this snippet:

/**
 * Enum containing a known-empty record type, matching only empty records unlike Object.
 *
 * @enum {Object}
 */
const Empty = {
    Record: {}
};

/**
 * Empty ItemQuery type, based on the Empty @enum.
 *
 * @typedef {Empty}
 */
export var EmptyItemQuery;

/**
 * Reference to the only EmptyItemQuery instance.
 *
 * @type {EmptyItemQuery}
 */
export const emptyItemQuery = Empty.Record;
  1. I used to think that JSDoc types must be defined in JSDoc comments only, but this code has used the Empty variable and the EmptyItemQuery variable (which are non-comment regular JavaScript variables) as types! I've checked JSDoc's doc and couldn't find a similar example, so I wonder if it's actually what I think it is? Or I'm misinterpreting it?

  2. For the emptyItemQuery, why not just do: export const emptyItemQuery = {};? Is the Empty object really needed here? What for?

CodePudding user response:

You are right. JavaScript does not know these types. As you said in your comment, they are only indicators for the IDE to help with code completion.

The author exports the object "emptyItemQuery" as an initialization value.

/**
 * 
 * @param {EmptyItemQuery} arg1 
 *
 */
function a1(arg1 = emptyItemQuery){}

Their naming convention will help contributors differentiate between generic and non-generic objects. They want to emphasize that the format to use for an empty query is {}, with whatever driver they used or created.

"Empty" being an enum, they will likely add more definitions in the future.

For instance:

export const Empty = {
    Record: {},
    Table: "*",
    Something: {}
};

export const emptyItemQuery = Empty.Record;
export const emptyTableQuery = Empty.Table;
export const emptySomethingQuery = Empty.Something;

The issue is that the enum Empty contains only 1 value. So, it makes the code look a bit more obscure as an enum with only one element defies the point.


Note that in the line:

export var EmptyItemQuery;

There is no use in exporting "EmptyItemQuery". It's likely a tiny mistake, as the symbol is never imported throughout the entire repository.


Finally, I think JsDocs is a fabulous tool. I always use it as it pushes code completion to a high level. It allows you to code quickly still (as you're using JavaScript) while having some type-checking abilities (without extra noise).

  • Related