beecomci / today_i_learned

0 stars 0 forks source link

[Typescript] Property 'value' does not exist on type 'EventTarget'. #27

Open beecomci opened 2 years ago

beecomci commented 2 years ago

이슈

const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {
      target: { value }
    } = event;

    setValue(value);
  };

return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          value={value}
          onChange={onChange}
          placeholder="username"
        />
        <button>Log in</button>
      </form>
    </div>
  );

원인

그럼 왜 EventTarget 타입은 Element 타입을 상속받지 않나 ?

해결 방안

1. Typescript에게 EventTarget의 정확한 타입 설명

const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    const target = event.target as HTMLInputElement;

    setValue(target.value);
  };

2. currentTarget