Subscribe on changes!

How to get the type of a Component instance?

avatar
Nov 10th 2020

Version

3.0.2

Reproduction link

None

Steps to reproduce

<template>
  <ChildComponent ref="child"/>
</template>

<script lang="ts">
  import {defineComponent} from 'vue'
  import {ref, onMounted} from 'vue'

  const ChildComponent = defineComponent({
    name: 'Child',
    setup() {
      const foo = ref(0)
      return {
        foo
      }
    },
  })

  export default defineComponent({
    setup() {
      const child = ref<(typeof ChildComponent)|null>(null)
      onMounted(()=>{
        child.value!.foo // issues described as below
      })
    },
    name: 'Parent',
    components: {
      ChildComponent
    },
  })
</script>

What is expected?

child.value!.foo // typeof foo is number with IDE autocomplete

What is actually happening?

child.value!.foo // typeof foo is any without any autocomplete

In vue2's vue class component, we can get the type of a component instance exactly.

avatar
Nov 10th 2020

I've found the solotion as below:

const child = ref<InstanceType<typeof ChildComponent>|null>(null)