본문 바로가기

개발하자

오른쪽 유형 스크립트 유형:Svelte에서 핸들러 변경

반응형

오른쪽 유형 스크립트 유형:Svelte에서 핸들러 변경

다음 코드가 있습니다.

<select class="form-control" on:change={pathChanged}>

의 서명은 다음과 같습니다.

function pathChanged(event: { target: HTMLSelectElement }) {

를 사용하여 실행 시 다음 오류가 발생합니다.

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}>

어떤 서명이 있어야 합니까?




그 사건은 당신이 원하는 것보다 덜 구체적이다. 이 시나리오에서는 일반적으로 함수 내에서 형식 어설션을 사용하여 이 문제를 해결합니다.

function pathChanged(event: Event) {
   const target = event.target as HTMLSelectElement;
   // ...
}

오류에 올바르게 입력해야 한다고 명시되어 있지만, 이를 사용하는 것도 효과적일 것입니다.

function pathChanged(event: { currentTarget: HTMLSelectElement })



입력 유형으로 이 작업을 수행했습니다.

// added this interface
interface FormEventHandler<T> {
    target: EventTarget | null;
}

// then in the function
const onChangeFile = async (event: FormEventHandler<HTMLInputElement>) => {
    const target = event.target as HTMLInputElement;
    // your code
}

반응형