Wednesday, September 24, 2025

Javascript: Avoiding the JsDoc

 We all want the types of Typescript without the Typescript, for the best friend to every human code generator: the members suggestion list that shows up after the dot.

But when you initilize a member with null in a Javascript class, obviusly the type infernece has no clue, so you need to add that JsDoc comment above:

constructor() {
  /** @type {Thing} */
  this.thing = null;
  /** @type {OtherThing} */
  this.target = null;
}

Yeah... adding a bunch of them after a while is not so elegant, breaks the flow, and also the verbosity doesn't realy help. Let's move the information from the comments to the actual code.

So we need something, like a function, that says that returns an object of a type, but just returns null, that also must be given the class, passing the class literal. Just, lookup how to denote a class, then add the JsDoc just there once to make it work:

/**
 * @template T
 * @param {new (...args: any[]) => T} c
 * @returns {T}
 */
function null_of(c) {
  return null;
}

And rewrite the constructor with it:

constructor() {
  this.thing = null_of(Thing);
  this.target = null_of(OtherThing);
}



done_