When using anonymous function with lodash debounce in my vue component for watch option, I got the typescript compiler error "this implicityly has type any.
Here is 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() // <= hear I got "this implicitly has type any"
}, 500)
}
}
})
I found on this post to use arrow function for my anonymous debounce callback function but the error still persists (TS2683 (TS) 'this' implicitly has type 'any' because it does not have a type annotation)
Another solution is to pass "this: any" as an argument to the function, but I found this very ugly.
_debounce(function(this:any, newValue){
this.load() // <= hear I got "this implicitly has type any"
}, 500)
Is there a better solution to handle this issue? (without setting noImplicitAny to false)
Try using 'arrow' function definition, to keep the scope of this
.
handler:_debounce(() => {
this.load()
}, 500)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
EDIT:
For this case, some design limitation in typescript makes it difficult to detect/assign a type to implicit this
(see
https://github.com/microsoft/TypeScript/issues/38845#issuecomment-651455328)
It should work using a function expression with typed parameter, defined in a custom Interface, for example:
interface ComponentInterface {
load(): void
}
And then:
_debounce(function(this:ComponentInterface, newValue){
this.load()
}, 500)
You can find several cases of defining types/annotations using this way at https://v3.vuejs.org/guide/typescript-support.html#using-with-options-api