Svelte 中 on:change 处理程序的正确 Typescript 类型
Right Typescript type for on:change handler in Svelte
我有这个代码:
<select class="form-control" on:change={pathChanged}>
pathChanged
的签名是:
function pathChanged(event: { target: HTMLSelectElement }) {
当我 运行 通过 tsc
使用 npm run check
时,我收到此错误:
Error: Type '(event: { target: HTMLSelectElement; }) => void' is not assignable to type 'FormEventHandler<HTMLSelectElement>'.
Types of parameters 'event' and 'event' are incompatible.
Type 'Event & { currentTarget: EventTarget & HTMLSelectElement; }' is not assignable to type '{ target: HTMLSelectElement; }'.
Types of property 'target' are incompatible.
Type 'EventTarget | null' is not assignable to type 'HTMLSelectElement'.
Type 'null' is not assignable to type 'HTMLSelectElement'. (ts)
<select class="form-control" on:change={pathChanged}>
pathChanged
应该有什么签名?
事件 target
没有您希望的那么具体。在这种情况下,我通常在函数中使用类型断言来解决这个问题。
function pathChanged(event: Event) {
const target = event.target as HTMLSelectElement;
// ...
}
尽管错误指出 currentTarget
应该输入正确,所以使用它应该也能正常工作:
function pathChanged(event: { currentTarget: HTMLSelectElement })
我有这个代码:
<select class="form-control" on:change={pathChanged}>
pathChanged
的签名是:
function pathChanged(event: { target: HTMLSelectElement }) {
当我 运行 通过 tsc
使用 npm run check
时,我收到此错误:
Error: Type '(event: { target: HTMLSelectElement; }) => void' is not assignable to type 'FormEventHandler<HTMLSelectElement>'.
Types of parameters 'event' and 'event' are incompatible.
Type 'Event & { currentTarget: EventTarget & HTMLSelectElement; }' is not assignable to type '{ target: HTMLSelectElement; }'.
Types of property 'target' are incompatible.
Type 'EventTarget | null' is not assignable to type 'HTMLSelectElement'.
Type 'null' is not assignable to type 'HTMLSelectElement'. (ts)
<select class="form-control" on:change={pathChanged}>
pathChanged
应该有什么签名?
事件 target
没有您希望的那么具体。在这种情况下,我通常在函数中使用类型断言来解决这个问题。
function pathChanged(event: Event) {
const target = event.target as HTMLSelectElement;
// ...
}
尽管错误指出 currentTarget
应该输入正确,所以使用它应该也能正常工作:
function pathChanged(event: { currentTarget: HTMLSelectElement })