0

"Exporting" a type from an old style js module.

How can I achieve ts-check and jsdoc compatibility when working with an old-style JavaScript module that selectively exports classes through this.ClassName = ClassName as shown below? We have a project with mostly ES5 code, we've been rewriting classes in ES6 syntax but switching to modern export/import modules would require significant refactoring. I have tried using @exports, @module, and other JSDoc annotations, but I'm unable to figure out how to accomplish this. Is it even possible to achieve ts-check and jsdoc compatibility in this scenario?

//@ts-check

(function () {
    class CMyClass {
        constructor() {
            /**@type {number} */
            this.Member = 1;
            console.log("constructor")
        }
    }

    /** @typedef {CMyClass} MyClass */
    /** @type {typeof CMyClass} */
    this.MyClass = CMyClass;

    /** @type {MyClass} */
    let b = new this.MyClass();
}).call(this)


/**@type {MyClass} */   <===== ERROR HERE: Cannot find name 'MyClass'.ts(2304)
let a = new this.MyClass();

To achieve type checking (ts-check) and documentation (jsdoc) compatibility for an old-style JavaScript module created through an immediately-invoked function expression (IIFE), I tried to use JSDoc annotations and ts-check. However, I couldn't find a way to make typescript understand that the class is actually available outside of the function's scope.

T Ledt
  • 1
  • 2

0 Answers0