본문 바로가기

What I Learnd/TIL

TIL - 새로고침을 막아주는 .preventDefault 메서드 → TS에서는?

타입스크립트로 투두리스트를 만들어주던 중 새로고침을 막아주는 e.preventDefault가 기존과 다르게 작동하는 것을 알게되었다. 

Problem

const addTodo = (e) => {
    e.preventDefault();
    const newTodo: Todo = {
      id: shortId.generate(),
      title: "New Todo Title 1",
      content: "New Todo Content 1",
      important: 1,
      dueDate: 20230730,
      createdAt: Date.now(),
      isCompleted: false,
      isDeleted: false,
    };

    setTodos([...todos, newTodo]);
  };
Parameter 'e' implicitly has an 'any' type.ts(7006)

'e'가 아무 타입이나 갖고있다며 에러가 난 상황!

 

Solve

TypeScript에서는 이벤트 핸들러의 매개변수에 타입을 반드시 명시적으로 지정해줘야 한다!

이벤트 객체의 타입은 React.MouseEvent 또는 React.FormEvent 등에 따라 달라지는데, 이 경우에는 폼(form) 이벤트를 처리하는 함수이므로 React.FormEvent를 사용하면 된다! → 필요할 때마다 검색이 필요해보임..!

먼저, addTodo 함수의 매개변수에 React.FormEvent를 명시적으로 지정하고, 폼 이벤트를 처리하기 위해 (이전과 동일하게) preventDefault() 메서드를 호출하여 새로고침을 막을 수 있었다!

import React, { FormEvent, useState } from "react";

{...}

  const addTodo = (e: FormEvent) => {
    e.preventDefault();
    const newTodo: Todo = {
      id: shortId.generate(),
      title,
      content,
      important: 1,
      dueDate: 20230730,
      createdAt: Date.now(),
      isCompleted: false,
      isDeleted: false,
    };

    setTodos([...todos, newTodo]);
  };