Error in Vue 3 Script Setup with Typescript: Implicit 'any' type for parameter 'el' in Template ref

Could someone help explain why I am receiving an error from TypeScript that says the following?

error TS7006: Parameter 'el' implicitly has an 'any' type. ref="(el) => saveRef(index, el)"
. I am confident that the correct type is set in the 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>

Answer №1

A best practice is to avoid redundant JS code in a template. One effective solution is to create a typed ref handler function in the component script. This function can be parametrized as a higher-order function:

function createRefHandler(
  index: number,
) {
  return (elem: ComponentPublicInstance<typeof FormComponent>) => {
    formRefs.value[index] = elem
  }
}

You can then use it like this:

:ref="createRefHandler(index)"
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

At what point is it appropriate for a class to incorporate an interface?

Currently working on a project and I've noticed developers using TypeScript in the following way: export class Ledger implements ILedger { LedgerID: number; CashAmmount: number; Units: number; ...

What is the best way to pass an object into a method within a select element using Vue

Kindly review the following code snippet. <tr> <td>Select Timeslot</td> <td colspan="2"> <select class="form-control" v-on:change="onTimeSlotClick"> <option v-for="slot of slots"> <l ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

Exploring custom dropdown Vuex: selecting between text content and HTML content

I'm currently developing a UI component that pulls values from a store. I'm trying to display the list item in the dropdown when clicked, but so far the click event is targeting all the routestart instead of just the one that was actually clicked ...

What is the best way to exhibit information from a get request within an option tag?

My GET request is fetching data from a REST API, and this is the response I receive: { "listCustomFields": [ { "configurationType": null, "errorDetails": null, "fieldId" ...

Applying the spread operator in the map function for copying objects

In my Angular application, I am attempting to copy an object and add a new property using the spread operator. To add the new property, I have created a method called 'addNewProperty(name)' which returns the property and its value. However, when ...

Resetting the index and length in Vue.js each time a new page is loaded

Currently facing an unusual issue that I'm struggling to resolve. My goal was to include an index number in a for-each loop and calculate the total count of data within my vue.js component. While I successfully achieved this, I encountered a problem w ...

Interval for Vuetify's carousel

I want to create a vuetify carousel for my website with different background images and text elements, but I'm facing an issue with the interval not working as expected. According to the Vuetify documentation, setting the "interval" attribute should f ...

Following an update from typescript version 2.3.4 to 2.4.2, I encountered a compilation error stating, "The type definition file for 'reflect-metadata' cannot be found."

Recently, I encountered an issue with my React / Mobex application written in TypeScript and built by Webpack 1. Upon updating the TypeScript version from 2.3.4 to 2.4.2, an error started occurring. The error message reads: ERROR in C:\myproject&bsol ...

What is the proper way to specify the type for a <video> element reference in React when utilizing Typescript?

I have been experimenting with controlling the play/pause state of a video in React.js using ref's. My code functions correctly but I am encountering tslint errors that I am currently trying to diagnose: function App() { const playVideo = (event:a ...

The process of filtering a model stops at the third character and results in an empty output

Whenever I input a value into the 'temp_dollars' model and use a watch property to filter it, the input only retains the first 3 characters and resets. For instance: When I type 123, The model value remains as 123. But wh ...

Encountering a timeout error when trying to test the video element with Jest

My function extracts meta data such as width and height from a video element in the following code snippet: export async function getVideoMetadata( videoBlobUrl: string, videoElement: HTMLVideoElement, ): Promise<{ width: number; height: number }> ...

How can one correctly cast or convert an array of objects to the interface that extends the objects' parent interface in Typescript?

Question: How can I optimize the usage of method sendItemIdsOverBroadcastChannel to reduce message size? interface IItemId { id: number; classId: number; } interface IItem extends IItemId { longString: string; anotherLongString: string } inte ...

Is there a way to pass a form error to the parent component as a parameter in React?

I am just starting to learn React. I have created a form and I want to inform the parent component about any input errors that occur. I attempted to use the variable myError as a prop similar to how I used the next method, but unfortunately, it did not wor ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

Adjust Column Title in Table

Is it possible to customize the column headers in a mat-table and save the updated value in a variable? I've been looking for a solution to this but haven't found one yet. ...

Is the TypeScript compiler neglecting the tsconfig.json file?

I am new to TypeScript and currently exploring how to set it up in WebStorm. One of the first steps I took was creating a tsconfig.json file in the main directory of my project and updating the built-in TypeScript compiler to version 1.6.2. However, despit ...

What is the process for updating input data after loading data from onSSR?

I've been encountering an issue with loading my shipping data from the server (onSSR) and updating it to my input form. Despite placing my code within onSSR as follows, the update does not occur: onSSR(async () => { await load(); await ...

Is it necessary to set up webpack for ES6 support?

I am encountering an issue with my Angular application that has a .tsconfig file set to target ES6. { "compileOnSave": false, "compilerOptions": { "allowJs": true, "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "de ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...