language-tools
language-tools copied to clipboard
Typing error: can't set object as event handler
Describe the bug
For DOM elements we can provide listeners as function and obj that implements handleEvent method.
In standart typeScript types for DOM present "EventListenerOrEventListenerObject" type, representing listener as obj, as on screenshot below:
In svelte I'm not able to pass such object as event handler, only function, because there is no overload for listener type.
The problem occurs only in types, the code is working just fine.
Reproduction
- create svelte-ts project (I used pnpm create vite -> svelte-ts)
- replace the code with the one below:
<script lang="ts">
let x = 'some text: ';
const obj = {
handleEvent() {
x+=1;
}
}
</script>
// ecpected handler type error on next line
<input on:input={obj}>
// ecpected handler type error on next line
<button on:click={obj}>1</button>
<br>
{x}
Expected behaviour
The types "MouseEventHandler", "FormEventHandler", etc. must have an overload for an event handler such as "EventListenerOrEventListenerObject".
System Info
- OS: Windows 10
- IDE: VSCode
- extension: Svelte for VS Code v107.5.1
Test project packages info:
- @sveltejs/vite-plugin-svelte: ^2.0.4
- @tsconfig/svelte: ^4.0.1
- svelte: ^3.58.0
- svelte-check: ^3.3.1
- tslib: ^2.5.0
- typescript: ^5.0.2
- vite: ^4.3.9
Which package is the issue about?
svelte-check
Additional Information, eg. Screenshots
No response
Why would you want to use events like this? TBH I'm not 100% sure this way of attaching events is intentionally supported.
It's useful when you need to create handler entities with their own data & methods, that is much clear with to do woth classes(objects), rather than functions created through scope
It's one of old native js API so it should be typed, like all base function .etc
Also I faced the problem with event handler type on base level
<script lang="ts">
export let handlerType1: () => void;
export let handlerType2: Function;
</script>
// invalid type in both cases
<button on:click={handlerType1}> ... </button>
<button on:keydown={handlerType1}> ... </button>
// valid type in both cases
<button on:click={handlerType2}> ... </button>
<button on:keydown={handlerType2}> ... </button>
Function
is not a type for a function. It's more of the base type for the object side of the function. Something like call
, apply
and name
. You can assign function to Function
but not the other way around.
https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABACxgCgJSIN4ChGK4C+upANgKZQowBMAXIgGLjTxIC8NA3LpdagDMjTIg4A+RADc4MACZiatXvxoAWRtkSZGM+YiKLUy-AUK45cCCAC2FMFAB0AQzlyAolPtQAMjADOUPYUAE5oAOQQZDAQANbhADRKGNxAA