typescriptvuejs3vue-tsc

vue ts type for current instance


I keep getting a ts error type:

Propery Instance does not exist on HTMLElement. I get my element in query selector and then in onmounted I access _instance. what type should I use to stop getting this error?

onMounted(() => {
  const myEl = document.querySelector('myHTMLElement') as HTMLElement

  nextTick(() => {
    if (myEl!== null)
      myEl._instance.exposed(someValue)
  })
})

the error is on myEl._instance.exposed(someValue)


Solution

  • TypeScript is correct: _instance does not exist on HTMLElement interface.

    If you have reason to believe it should exist in this particular case, you have to let TS in on the secret:

    interface SomeElement extends HTMLElement {
      _instance: {
        // update if you want type checking on arg0:
        exposed: (arg0: unknown) => void
      }
    }
    
    onMounted(() => {
      const myEl: SomeElement | null = document.querySelector("some-element")
    
      nextTick(() => {
        myEl?._instance.exposed(someValue)
      })
    })
    

    Side note: you should not use document.querySelector in a Vue app. Use template refs instead.