In my project, I am working with a component called A that has a method called send
.
Here is an example of how Component A is structured in A.vue:
<script setup lang="ts">
function send(data: string) {
console.log(data)
}
defineExpose({ send })
</script>
Now, I have another component called B which imports Component A.
This is how B.vue looks:
<template>
<ComponentA ref="a" />
</template>
<script setup lang="ts">
import ComponentA from '@/component-a.vue'
const a = ref()
onMounted(() => a.value.send(22)) // there should be a type error here
</script>
My question is, how can I properly type the imported component so that when calling its methods through refs, it validates the method names and argument types?
I tried using
ComponentPublicInstance<typeof ComponentA>
as found through research, but it doesn't seem to perform the desired method checks.
UPDATE:
Below is the content of shims-vue.d.ts (generated by vue-cli):
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
UPDATE:
For a full reproduction scenario, please check out the repository.
As shown in the HelloWorld.vue file, the variable a
is a ref to an instance of ComponentA. I attempted to type it using
const a = ref<InstanceType <typeof ComponentA>>()
, but unfortunately, it still gets typed as any
.