2024.03.05 TIL - typescript 트러블슈팅(form태그 input type오류, styled-components props type오류, setState props내려주기, RTK useSelector type오류)

Innes·2024년 3월 5일
0

TIL(Today I Learned)

목록 보기
82/147
post-thumbnail

🏹 트러블슈팅

문제1. form태그의 input값 type오류

  • 문제 : form태그의 자식요소 input 값을 e.target.title.value 이런식으로 지정했는데, EventTarget형식에 속성이 없다는 에러가 나온다.

  • 시도 1 : target 대신 currentTarget 사용
    (참고 : https://nuhends.tistory.com/115)

  • 새로운 오류 발생 : 아래 둘은 괜찮은데, 첫번째 title의 value에서 문제가 발생한다.

  • 해결 : 'title'을 'titleValue'로 바꿔주니 해결됨....?! 오잉

   const titleValue = e.currentTarget.titleValue.value;
  • e.currentTarget에 title이라는 예약어같은게 들어있었는지...? title일땐 에러떴는데 titleValue하니까 에러가 없어졌다. 오잉
    (아래 input태그의 name도 titleValue로 함께 바꿔줌)

styled-components props type 오류

  • 컴포넌트 에러


  • styled-components 에러
  • 문제 : styled-components에 props로 내려주는 로직 $isDone에서 오류 발생

  • 원인 : styled-components에서 props로 받을 때 type을 지정해주지 않아서 오류가 발생했다.

// 문제의 코드

export const CompleteBtn = styled.button`
  width: 80px;
  margin-bottom: 10px;

  color: rgb(91, 91, 91);
  background-color: ${(props) =>
    props.$isDone ? css`rgb(101, 161, 211)` : css`rgba(235, 154, 2, 0.92)`};
  border: 0px;
  border-radius: 10px;
  color: white;
`;

  • 해결 : $isDone의 타입을 지정해주니 오류 해결
export const CompleteBtn = styled.button<{ $isDone: boolean }>` // ⭐️ type지정!
  width: 80px;
  margin-bottom: 10px;

  color: rgb(91, 91, 91);
  background-color: ${(props) =>
    props.$isDone ? css`rgb(101, 161, 211)` : css`rgba(235, 154, 2, 0.92)`};
  border: 0px;
  border-radius: 10px;
  color: white;
`;

(참고 : https://velog.io/@altjsvnf/TS-TypeScript%EC%97%90%EC%84%9C-Styled-component-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0)


setState를 props로 내려주기(ts)

  • React.FC< T > : T부분에 type을 넣어주면 되는거였다!

  • 시도

import { Todo } from "../types/Todos";

type TodoListProps = {
  todos: Todo[];
  setTodos: React.Dispatch<React.SetStateAction<Todo[]>>;
};

// ❌ { todos, setTodos } : TodoListProps
const TodoLists: React.FC = ({ todos, setTodos }: TodoListProps) => {
  const workingTodos = todos.filter((todo) => !todo.isDone);
  const doneTodos = todos.filter((todo) => todo.isDone);
  
  return (// ...생략)
  • 성공
import { Todo } from "../types/Todos";

type TodoListProps = {
  todos: Todo[];
  setTodos: React.Dispatch<React.SetStateAction<Todo[]>>;
};

// ✅ React.FC<TodoListProps>
const TodoLists: React.FC<TodoListProps> = ({ todos, setTodos }) => {
  const workingTodos = todos.filter((todo) => !todo.isDone);
  const doneTodos = todos.filter((todo) => todo.isDone);
  
  return (// ...생략)

RTK 변환 중 typescript 오류

  • 문제 : 평소처럼 dispatch, useSelector 했더니 오류메시지 발생

  • 시도

// 📝 컴포넌트

import InputBox from "../components/InputBox";
import Header from "../layout/Header";
import TodoLists from "../components/TodoLists";
import { useSelector } from "react-redux";

const Home: React.FC = () => {
  const todos = useSelector((state) => state.todoReducer);
  // ❌ 에러 : 'state'는 unknown 형식입니다.
  // 시도 : state: Todo[]
  // -> todoReducer에서 'Todo[]에 todoReducer 속성이 없습니다' 에러 발생
  return (
    <div>
      <Header />
      <InputBox />
      <TodoLists todos={todos} />
    </div>
  );
};

export default Home;

// 📝 configStore

import { configureStore } from "@reduxjs/toolkit";
import { todoReducer } from "../modules/todoSlice";

export const store = configureStore({
  reducer: { todoReducer },
});
  • 해결
// 📝 컴포넌트

import InputBox from "../components/InputBox";
import Header from "../layout/Header";
import TodoLists from "../components/TodoLists";
import { useAppSelector } from "../redux/config/configStore";

const Home: React.FC = () => {
  // ⭐️⭐️ configStore에서 선언해준 useAppSelector 사용하기!
  const todos = useAppSelector((state) => state.todoReducer);
  return (
    <div>
      <Header />
      <InputBox />
      <TodoLists todos={todos} />
    </div>
  );
};

export default Home;

// 📝 configStore

import { configureStore } from "@reduxjs/toolkit";
import { todoReducer } from "../modules/todoSlice";
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";

export const store = configureStore({
  reducer: { todoReducer },
});

// ⭐️⭐️ useDispatch, useSelector를 여기서 타입 지정해서 선언을 한번 해주네! 신기
// 근데 dispatch는 useAppDispatch하니까 오류나고 그냥 일반 dispatch하니까 잘된다....?
export const useAppDispatch: () => typeof store.dispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<
  ReturnType<typeof store.getState>
> = useSelector;

💦 아직 이게 어떻게 해결된건진 모르지만...
일단 useSelector 오류메시지는 유튜브보고 해결함...
https://www.youtube.com/watch?v=EqbwHO6Vgbg

profile
꾸준히 성장하는 우상향 개발자

0개의 댓글