만날 문서로 보고 눈으로 봐도 쳐보는 것만 못하다라는 우리의 응국슨상님 말처럼 간단한 TodoList를 한번 만들어 보려고 한다.
사실 이거 어렵다. 타입 하나하나 다 지정해주고, 오류에 진절머리치고 소스라 치는 나한테는 더더욱 어렵다. 그리고 타입스크립트를 잘 다룰 수 있다는 말은 즉슨, props의 구조와 함수의 플로우를 다 아는 경우에 자유롭게 다룰 수 있는데 아직 배우는 단계인 나로서는 조금 어렵다.
하지만 열심히 할꺼다. 왜냐고? 가방사고 맛있는거 많이 먹을려구 나중에 ^^! 그럴라면 돈이 많아야 하잖음?? 연봉을 올리면 돈이 많아지잖씀?? 그래서 더 열심히 할 꺼임 💪🏻💘💞💕 // 헛소리 끝 ㅎㅎ
유튜브에 검색해 나온 외국엉아들 중 그나마 조금 쉽게 설명된 Tuts 엉아의 강의를 들으면서 참고했음. 포스팅은 혼자 개념 / 플로우 이해하는 방향으로 할꺼임!
//App.tsx import React from "react"; import { TodoListItem } from "./TodoListItem"; const App: React.FC = () => { const todos = [ { text: "watch the movie", completed: false }, { text: "eat the dinner", completed: true }, ]; return ( <React.Fragment> <TodoListItem /> </React.Fragment> ); }; export default App;
//TodoListItem.tsx import React from "react"; export const TodoListItem: React.FC = ({}) => { return <li>hello</li>; };
return ( <React.Fragment> <TodoListItem todos={todos} /> </React.Fragment> );
Type 설정을 안해줘서 가차없이 바로 에러남 흐미 ㅜㅜ
App.tsx
type Todo = { text: string; //obj text의 타입은 string completed: boolean; //obj completed 타입은 boolean }; const App: React.FC = () => { const todos: Array<Todo> = [ //todos의 타입은 array이고 그 안에 들어오는 요소는 Todo가 갖고 있는 타입이 들어옴. { text: "watch the movie", completed: false }, { text: "eat the dinner", completed: true }, ]; {...reuturn 생략}
즉 , [...{text:string,completed:boolean}]
이런 타입이 들어온다는 의미임.
배열 안 요소는 generic으로만 가져올 수 있음.
근데 이렇게 해도 애러남^^ 애러이유는 부모 컴포넌트에서만 props 타입을 지정해줬기 때문임. props를 전달받는 자식 컴포넌트에도 props 타입을 설정해줘야함.
TodoListItem.tsx
import React from "react"; type Todo = { text: string; completed: boolean; }; interface TodoListItemProps { todos: Array<Todo>; } export const TodoListItem: React.FC<TodoListItemProps> = ({ todos }) => { return <li>hello</li>; };
근데 type부분이 겹침! type.ts 파일 생성해서 겹치는 타입 빼주기.
//type.ts type Todo= { text: string, completed: boolean }
✨ Tip : name.d.ts 로 파일명을 바꿔주면 export 없이도 type을 어디서든 사용할 수 있음!
//UserListItem.tsx import React from "react"; interface TodoListItemProps { todos: Array<Todo>; } export const TodoListItem: React.FC<TodoListItemProps> = ({ todos }) => { return ( <> {todos.map((todo) => ( <li key={todo.text}>{todo.text}</li> ))} </> ); };
이런 식으로 props를 전달해줄때, 전달 받을 때 모든 컴포넌트에서 type을 정해줘야 한다. 이게 타입스크립트의 역활이라는걸 잊지말기!
이렇게 자식 컴포넌트에 props로 잘 들어가는걸 확인했으니, UI에 맞게 요래저래 컴포넌트도 설정하고, 전달하고 전달받는 함수들도 다 타입을 지정해주면서 포스팅을 할꺼임!