Home > Enterprise >  Write class declaration for jsdoc
Write class declaration for jsdoc

Time:03-22

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?

CodePudding user response:

I think what you need is to use typeof here:

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