The Vue Typescript callback is automatically assigned the type "any" when not explicitly defined

Encountering a TypeScript compiler error while using an anonymous function with lodash debounce in my Vue component's watch option. The error states: "this implicitly has type any."

Below is the code snippet of my component:

export default defineComponent({
  data(){
    return {
       filters:{
          filter1: "foo"
       } as Record<string, string>
    }
  },
  methods:{
    load(){
       //load function
    },
  },
  watch:{
    "filters":{
       deep: true,
       handler:_debounce(function(newValue){
           this.load() // <= here I got "this implicitly has type any"
       }, 500)
     }
   }
})

After researching, I tried using an arrow function for the anonymous debounce callback function as suggested in this post. However, the error persisted (TS2683(TS) 'this' implicitly has type 'any' because it does not have a type annotation).

Another workaround involves passing "this: any" as an argument to the function, but this method is considered unsightly.

_debounce(function(this:any, newValue){
           this.load() // <= here I got "this implicitly has type any"
       }, 500)

Is there a more elegant solution to address this issue without resorting to setting noImplicitAny to false?

Answer №1

To maintain the scope of this, consider using 'arrow' function definition.

handler:_debounce(() => {
       this.load() 
   }, 500)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

UPDATE: In certain scenarios, TypeScript's design limitations might pose challenges when identifying or assigning a type to implicit this (refer to https://github.com/microsoft/TypeScript/issues/38845#issuecomment-651455328) One potential solution is to use a function expression with typed parameter within a custom Interface, like so:

interface ComponentInterface {
  load(): void
}

Subsequently:

_debounce(function(this:ComponentInterface, newValue){
       this.load()
   }, 500)

Various examples of defining types/annotations can be found in this manner at https://v3.vuejs.org/guide/typescript-support.html#using-with-options-api

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

Received corrupted file during blob download in Angular 7

When using Angular 7, I am making an API call by posting the URL file and attempting to download it using the 'saveAs' function from the fileSaver library. The file is successfully downloading, but it appears to be corrupted and cannot be opened. ...

What type of value does a `use` directive return?

Upon reviewing the svelte tutorial, I observed that the clickOutside function provides an object with a destroy method. What should be the precise return type of a custom use directive? export function clickOutside(node: HTMLElement): ??? { // Initia ...

Only implement valueChanges on the second step of the form

I am utilizing the mat-stepper with a single form. My stepper has two steps only. I am looking to make an API request for every input value change, but only when the user is on the second step. How can I accomplish this? .ts ngOnInit() { this.formGr ...

When working with Angular 5, the question arises: how and where to handle type conversion between form field values (typically strings) and model properties (such

As a newcomer to Angular, I am struggling with converting types between form field values (which are always strings) and typed model properties. In the following component, my goal is to double a number inputted by the user. The result will be displayed i ...

Guide on implementing the Translate service pipe in Angular 2 code

So here's the issue... I've integrated an Angular 4 template into my application which includes a functioning translate service. The only problem is, I'm unsure of how to utilize that pipe in my code. In HTML, it's as simple as adding ...

Using mapState on a module that is not namespaced

Question about a module export default { namespaced: false, state, actions, mutations, getters }; In one of my components, I attempted the following: ...mapState(["user"]), ...mapState('auth',["user"]), Unfortunately, neither of t ...

Can we create a generic constraint that utilizes an index, be it a type or an object?

I am currently generating client models (Entities) along with their corresponding Primary Keys. My goal is to create a method signature where, based on the Entity provided, the second parameter should be its Primary Key only. The specific use of types an ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

When a button is clicked in (Angular), it will trigger the highlighting of another button as a result of a value being modified in an array. Want to know the

Currently in the process of developing a website with Angular, I've encountered an unusual bug. The issue arises when using an *ngFor div to generate twelve buttons. <div *ngFor = "let color of colors; let i = index" style = "display ...

Setting up next-i18next with NextJS and Typescript

While using the next-i18next library in a NextJS and Typescript project, I came across an issue mentioned at the end of this post. Can anyone provide guidance on how to resolve it? I have shared the code snippets from the files where I have implemented the ...

What is the best way to utilize two values in Vue.js 2?

When I attempt to structure my component in the following way: <script> export default { template: '\ <select class="form-control" v-on:change="search">\ <option v-for="option in option ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

Retrieving the Final Value from an Observable in Angular 8

Is there a way to retrieve the most recent value from an Observable in Angular 8? let test = new BehaviorSubject<any>(''); test.next(this.AddressObservable); let lastValue = test.subscribe(data=>console.log(data.value)); Despite my ef ...

Is it possible to associate non-HTML elements such as v-btn with Nuxt's tag prop?

Here is the code I have been working on in my editor: <nuxt-link :to="www.test.com" tag="v-btn" /> Link Button </nuxt-link> I realized that v-btn is not a standard HTML tag, but rather a specific one for Vuetify. When I write the code this wa ...

Ensuring the correctness of a date input with v-validate in Vue.js

I need to set a condition where only dates that are equal to or greater than the departure date time field are allowed: <tr v-for="(input,k) in inputs" :key="k"> <datetime name="departureDateTime" v-validat ...

Ways to bring in a Typescript Vue project to a Javascript Vue

I am trying to incorporate this Calendar component into my Javascript Vue 3 project. To achieve this, I have created a new component in my project named ProCalendar.vue and copied the code from the example found in App.vue. Additionally, I have added the n ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

Change the Angular Material 2 theme from light to dark with a simple click

I'm working on an Angular 2 Material project and I want to be able to switch the theme from dark to light with a single click of a button. Can anyone help me figure out how to achieve this? Any tips or advice would be greatly appreciated! ...

Managing multiple Sequelize DB connections in NestJS: A guide

I recently came across the example in the NestJS documentation regarding setting up a Sequelize DB connection. I'm curious about how to connect to multiple databases using Sequelize and TypeScript with NestJS. Can anyone provide guidance on this? ...