'Vue 3 Script Setup Typescript | Template ref: Parameter 'el' implicitly has an 'any' type
Can anyone tell me why typescript is yelling at me with the following error?
error TS7006: Parameter 'el' implicitly has an 'any' type. ref="(el) => saveRef(index, el)". I'm pretty sure correct type is set in saveRef function.
<script lang="ts" setup>
import FormComponent from '@/components/FormComponent.vue'
const formRefs = ref<
ComponentPublicInstance<typeof FormComponent>[]
>([])
function saveRef(
index: number,
el: ComponentPublicInstance<typeof FormComponent>
) {
formRefs.value[index] = el
}
onBeforeUpdate(() => {
formRefs.value = []
})
</script>
<template>
<div v-for="(component, index) in components" :key="index">
<form-component
:ref="(el) => saveRef(index, el)"
:component="component"
:index="index"
/>
</div>
</template>
Solution 1:[1]
It's generally not a good practice to keep redundant JS in a template. A proper solution is to define typed ref handler function in component script. Since it's supposed to be parametrized, it can be higher-order function:
function saveRef(
index: number,
) {
return (el: ComponentPublicInstance<typeof FormComponent>) => {
formRefs.value[index] = el
}
}
And use it as :ref="saveRef(index)".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Estus Flask |
