- yarn create react-app 폴더명 --template typescript 로 설치
- index.tsx 파일 바꿔주기
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
- TodoListItem.tsx 컴포넌트 만들기
interface TodoListItemProps {
todo: {
text:string,
complete:boolean
};
}
export const TodoListItem: React.FC<TodoListItemProps> = ({ todo }) => {
return (
<li>
<label>
<input type="checkbox" checked={todo.complete} />
{todo.text}
</label>
</li>
);
};
- types.d.ts 컴포넌트 파일을 만들어주어 타입들만 모여있는 파일을 만든다. 이 때 types.ts가 아닌 types.d.ts로 파일명을 만들게 되면 이 파일에 decoration을 해줌으로서 따로 import를 하지 않아도 된다.
type Todo = {
text: string;
complete: boolean;
};
- Todo라는 타입을 만들어주었기 때문에 import 없이 적용시킬 수 있다.
interface TodoListItemProps {
todo: Todo;
}
export const TodoListItem: React.FC<TodoListItemProps> = ({ todo }) => {
return (
<li>
<label>
<input type="checkbox" checked={todo.complete} />
{todo.text}
</label>
</li>
);
};
import React from "react";
import { TodoListItem } from "./TodoListItem";
const todos: Array<Todo> = [
{ text: "밥 먹기", complete: true },
{ text: "옷 입기", complete: false },
];
const App: React.FC = () => {
return (
<React.Fragment>
<TodoListItem todo={todos[0]} />
<TodoListItem todo={todos[1]} />
</React.Fragment>
);
};
export default App;