타입스크립트로 투두리스트를 만들어주던 중 새로고침을 막아주는 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]);
};
'What I Learnd > TIL' 카테고리의 다른 글
TIL - Styled-Components 리액트 스타일링 하기 (0) | 2023.07.31 |
---|---|
TIL - TypeScript에서 Styled Components 라이브러리 사용하기 step by step (0) | 2023.07.30 |
TIL - React 전용 TypeScript 셋업 step by step / TypeScript에서 모듈 설치하기 (0) | 2023.07.28 |
TIL - TypeScript 객체 지향 프로그래밍 (0) | 2023.07.27 |
TIL - TypeScript 컴파일러, tsc 설정변경! (0) | 2023.07.25 |