1

I write a simple class and a declaration for it. Then I use jsdoc to specify the type of lib.

// index.ts
class VjsccXX {
  el: HTMLElement
  text: string
  show: boolean

  constructor(el: HTMLElement, text: string, show = true) {
    this.el = el
    this.text = text
    this.show = show

    this.el.classList.add('vjsscc-xx')

    if (!show) {
      this.el.style.display = 'none'
    }

    console.log('xx is ready')
  }
  hide() {
    this.el.style.display = 'none'
  }
  tex() {
    this.el.innerHTML = this.text
  }
}

export default VjsccXX
// index.d.ts
declare class VjsccXX {
  el: HTMLElement
  text: string
  show: boolean
  hide(): void
  tex(): void
  constructor(el: HTMLElement, text: string, show?: boolean)
}

export = VjsccXX
// test.js
/** @type {import('..')} */
const VjsccXX = window.VjsccXX

enter image description here

But as the photo shown above, VjsccXX become a instance rather than a class. So how to deal with it?


======================= Some Update ==========================

The image shown above use a window.VjsccXX because its html file include a umd bundle. And its type is not right because VjsccXX should be a class constructor rather than a class instance which has prototype properties.

Then I write another ts file to see its type:

enter image description here

Maybe I could write like that?

======================= Another update ============================

Also work with cjs:

enter image description here

enter image description here

enter image description here

Maybe it is the problem of jsdoc?

GuangWu
  • 378
  • 4
  • 14
  • What would you expect to have? You are creating a variable with the same name as your class definition and indicate with `@type` that it has the type of your class. Everything seems to be working as expected here. – Ben Mar 16 '22 at 10:19
  • Becasue after `umd` build, the `VjsccXX` will be added to `window`. And I declare a new variable with same name is no conflict. Then I use jsdoc to specific the type of it to get the right type. And its type is not right, `VjsccXX` should be a constructor rahter than a instance which has properties on class prototype. – GuangWu Mar 17 '22 at 01:58

2 Answers2

1

I think what you need is to use typeof here:

// test.js
/** @type {typeof import('..')} */
const VjsccXX = window.VjsccXX
Ben
  • 1,331
  • 2
  • 8
  • 15
0

What about creating an interface instead of a class declaration in index.d.ts?

// index.d.ts
export interface IVjsccXX {
  el: HTMLElement;
  text: string;
  show: boolean;
  hide(): void;
  tex(): void;
}

Then you may use it in jsdocs:

// test.js
/** @type {import('..').IVjsccXX} */
const VjsccXX = window.VjsccXX;

However, the constructor handling for interfaces in TS is a mess to me, if interested you may refer to How does interfaces with construct signatures work? for details.

Evi Song
  • 862
  • 11
  • 14