본문으로 건너뛰기

할 일 화면을 TS로 옮기기

리액트 목차 TS로 쓰기 레슨 61 / 61

목차

이 레슨은 단원 8 끝의 할 일 화면 파일을 todo-ts 프로젝트로 옮긴 뒤, 다른 파일이 가져다 쓰는 파일부터 하나씩 .tsx · .ts로 바꾸며 검사 오류를 고쳐 npm run build를 오류 0으로 지나게 합니다.

이 단계 시작 파일은 useLocalStorage로 저장 빼기 레슨 예제의 파일 아홉(접기)과 src/App.jsx(끝 조각 접기), 정적인 판 레슨 3절의 src/index.css입니다. 단원 9에서 폼 액션으로 고친 판은 옮기지 않습니다.

ts-setup에서 만든 todo-ts에서 씁니다. 검사는 npx tsc -b로 하고, 결과 상자는 ts-setup 4절처럼 오류를 한 줄 꼴로 적습니다. TS 과목의 JS 코드에 타입 붙이기 · 제네릭 — 부를 때 채우는 타입 칸 · 바깥 값 확인하기를 마쳤다고 보고 씁니다. 옮기는 틀은 'JS 코드에 타입 붙이기'의 하위 목표 넷을 컴포넌트에 맞춘 것입니다.

하위 목표하는 일이 레슨의 코드
1. props 모양을 interface로props와 children에 타입의 꼴TodoListProps 따위
2. 빈 state에 타입state에 타입의 칸<Todo[]>
3. 이벤트 · ref에 타입이벤트 · ref에 타입의 꼴InputChangeEvent 따위
4. 검사하며 하나씩 고치기파일 하나를 바꿀 때마다 검사한다npx tsc -b

4단계 중 1단계. 1. JS 판 파일을 todo-ts로 옮겨 넣기. JS 판 파일을 옮겨 넣으면 .tsx가 .jsx를 가져오는 줄에서 TS7016이 납니다. 옮기는 동안만 allowJs로 JS 파일도 받습니다.

1JS 판 파일을 todo-ts로 옮겨 넣기

틀이 만든 src/App.tsx · src/App.css를 지우고 시작 파일을 같은 자리(src/ · public/)에 넣습니다. src/index.css는 덮어씁니다. src/main.tsx는 지운 파일 대신 .jsx를 가져오게 4번 줄을 바꿉니다.

src/main.tsx
import App from './App.jsx'

npm run dev의 화면은 단원 8과 같지만, 검사하면 TS7016 하나가 납니다. .tsx가 가져온 ./App.jsx의 타입을 알 길이 없어 any로 본다는 뜻입니다. 틀의 tsconfig.app.json은 .ts · .tsx만 프로젝트 파일로 받습니다.

결과 보기

…는 todo-ts 폴더까지의 경로라 컴퓨터마다 다릅니다.

검사 결과 오류 1개
src/main.tsx(4,17): error TS7016: Could not find a declaration file for module './App.jsx'. '…/todo-ts/src/App.jsx' implicitly has an 'any' type.

옮기는 동안만 그 파일의 "noEmit": true, 아래에 "allowJs": true, 한 줄을 더해 JS 파일도 받습니다. 타입스크립트 문서는 이 옵션을 JS 프로젝트에 TS 파일을 조금씩 더해 가는 길로 소개합니다. 다시 검사하면 아무것도 찍지 않고 끝납니다.

2가져다 쓰이는 파일부터 — props 모양을 interface로

이제 가져다 쓰이는 쪽부터 한 파일씩 바꿉니다 — TodoItem → TodoList → TodoFilters → TodoFooter → TodoForm → api · Quote → useLocalStorage → App. 그래야 가져오는 쪽을 바꿀 때 넘기는 값이 이미 선 props 타입과 맞춰집니다. 거꾸로면 아직 .jsx인 쪽이 받는 모양을 알리지 않아, 틀린 값을 넘겨도 지나갑니다.

먼저 할 일 모양 Todo를 src/types.ts에 둡니다(ts-setup 예제와 같은 파일). TodoItem.jsx를 .tsx로 바꾸고 검사하면 TS7031 셋(todo · onToggle · onDelete)입니다. 구조 분해로 꺼낸 props도 함수의 매개변수라, 타입이 추론되지 않아 any가 됐다는 뜻입니다(TS7006과 같은 까닭). 이름만 바꾸면 TS가 되는 것이 아니라, 이 오류가 할 일입니다. 모양을 interface TodoItemProps⁠로 적어 머리 끝에 붙이면 0입니다.

결과와 코드 보기

결과 상자입니다.

검사 결과 오류 3개
src/TodoItem.tsx(2,3): error TS7031: Binding element 'todo' implicitly has an 'any' type.src/TodoItem.tsx(3,3): error TS7031: Binding element 'onToggle' implicitly has an 'any' type.src/TodoItem.tsx(4,3): error TS7031: Binding element 'onDelete' implicitly has an 'any' type.
src/types.ts
export type Todo = {
  id: number;
  text: string;
  done: boolean;
};
src/TodoItem.tsx
import type {
  Todo,
} from './types.ts';

interface TodoItemProps {
  todo: Todo;
  onToggle: (
    id: number,
  ) => void;
  onDelete: (
    id: number,
  ) => void;
}
…
}: TodoItemProps) {

TodoList.tsx는 넷입니다. 같은 TS7031 셋과, todos.map((todo) => …)⁠의 todo에 난 TS7006입니다. interface TodoListProps⁠에 todos: Todo[]와 함수 둘을 적으면 넷이 함께 사라집니다. todo는 map에 넘긴 함수 자리에서 Todo로 정해집니다(이벤트 · ref에 타입 1절의 '문맥').

결과 보기

결과 상자입니다.

검사 결과 오류 4개
src/TodoList.tsx(5,3): error TS7031: Binding element 'todos' implicitly has an 'any' type.src/TodoList.tsx(6,3): error TS7031: Binding element 'onToggle' implicitly has an 'any' type.src/TodoList.tsx(7,3): error TS7031: Binding element 'onDelete' implicitly has an 'any' type.src/TodoList.tsx(18,19): error TS7006: Parameter 'todo' implicitly has an 'any' type.

TodoFilters.tsx(둘 — filter · onChange)와 TodoFooter.tsx(셋)도 같은 꼴로 0이 됩니다(예제).

3TodoForm — 이벤트 · ref에 타입

TodoForm.tsx는 넷입니다(onAdd의 TS7031 · 두 핸들러 e의 TS7006 · inputRef.current의 TS18047). 앞 레슨의 꼴로 하나씩 고치며 센 남은 오류입니다.

고친 곳남은 오류
props — interface TodoFormProps3
사건 — e: InputChangeEvent 따위1
ref — useRef<HTMLInputElement>(null)1
focus() 줄을 if (inputRef.current)⁠로 감쌈0
결과와 코드 보기

이름만 바꾼 판의 결과 상자입니다.

검사 결과 오류 4개
src/TodoForm.tsx(6,21): error TS7031: Binding element 'onAdd' implicitly has an 'any' type.src/TodoForm.tsx(11,25): error TS7006: Parameter 'e' implicitly has an 'any' type.src/TodoForm.tsx(15,25): error TS7006: Parameter 'e' implicitly has an 'any' type.src/TodoForm.tsx(17,5): error TS18047: 'inputRef.current' is possibly 'null'.

고친 끝 판입니다. 사건 타입은 맨 바깥 별칭에 담고, type을 붙인 이름은 값 이름 뒤에 둡니다.

src/TodoForm.tsx
import {
  useRef,
  useState,
  type ChangeEvent,
  type SubmitEvent,
} from 'react';

type InputChangeEvent =
  ChangeEvent<HTMLInputElement>;
type FormSubmitEvent =
  SubmitEvent<HTMLFormElement>;

interface TodoFormProps {
  onAdd: (text: string) => void;
}

function TodoForm({
  onAdd,
}: TodoFormProps) {
  // 4. state 자리 정하기
  const [text, setText] =
    useState('');
  const inputRef =
    useRef<HTMLInputElement>(
      null,
    );
  function handleChange(
    e: InputChangeEvent,
  ) {
    setText(e.target.value);
  }
  // 5. 바꾸는 일은 위로 알리기
  function handleSubmit(
    e: FormSubmitEvent,
  ) {
    e.preventDefault();
    if (inputRef.current) {
      inputRef.current.focus();
    }
    const value = text.trim();
    if (value === '') return;
    onAdd(value);
    setText('');
  }
  return (
    <form
      id="todo-form"
      onSubmit={handleSubmit}
    >
      <label
        htmlFor="todo-input"
      >
        할 일
      </label>
      <input
        ref={inputRef}
        id="todo-input"
        value={text}
        onChange={handleChange}
      />
      <button>추가</button>
    </form>
  );
}

export default TodoForm;

ref 칸을 채워도 하나가 남는 것은 첫 값 null도 타입에 들어서라, if로 좁힌 안에서 focus()를 부릅니다. api.ts · Quote.tsx는 이름만 바꿔도 0입니다. 적지 않은 매개변수가 없고, res.json()이 돌려주는 값은 any라 검사기가 맞춰 볼 것이 없습니다.

4useLocalStorage와 App

훅을 .ts로 바꾸면 셋(key · initial의 TS7006과 JSON.parse의 TS2345)입니다. 제네릭으로 <T> · key: string · initial: T · load(): T를 적어도 TS2345 하나가 남습니다. getItem은 없는 키에 null을 돌려주는데 JSON.parse의 선언은 글(string)만 받습니다. 실행 때는 JSON.parse(null)이 null이라 JS 판이 ?? initial로 돌았지만, 검사기는 선언만 봅니다. 그 앞에서 raw가 null이면 처음 값을 돌려주면 0입니다.

결과와 코드 보기

<T>를 적은 판의 결과 상자입니다.

검사 결과 오류 1개
src/useLocalStorage.ts(15,18): error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'.  Type 'null' is not assignable to type 'string'.
src/useLocalStorage.ts
function useLocalStorage<T>(
  key: string,
  initial: T,
) {
  function load(): T {
    const raw = localStorage
      .getItem(key);
    if (raw === null) {
      return initial;
    }
    const saved =
      JSON.parse(raw);
    return saved ?? initial;
  }

JSON.parse의 값은 any라, load(): T는 저장된 글이 T 모양이라는 말을 검사기가 믿을 뿐 실행 때 보지는 않습니다. 실행 때 확인하려면 '바깥 값 확인하기'의 확인 함수를 씁니다.

App.jsx를 .tsx로 바꾸고 main.tsx 4번 줄을 './App.tsx'로 되돌리면 21건이고, 오류 글에 빈 배열의 never[]가 보입니다. state에 타입처럼 칸을 채우고 Todo를 가져옵니다.

src/App.tsx
import type {
  Todo,
} from './types.ts';
…
    useLocalStorage<Todo[]>(
      'todos',
      [],
    );

맞혀 봅니다. 칸을 채운 뒤 다시 검사하면 21건은 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 0이 된다 — todos가 Todo[]라 모두 맞는다
  • ② 넷만 남는다 — 타입을 적지 않은 매개변수 list · text · id 둘
  • ③ 21건 그대로 — 오류 글의 never[]만 Todo[]로 바뀐다
결과 보기

③입니다. 결과 상자입니다.

검사 결과 오류 21개
src/App.tsx(20,20): error TS7006: Parameter 'list' implicitly has an 'any' type.src/App.tsx(43,22): error TS7006: Parameter 'text' implicitly has an 'any' type.src/App.tsx(49,5): error TS2349: This expression is not callable.  Not all constituents of type 'Todo[] | Dispatch<SetStateAction<Todo[]>>' are callable.    Type 'Todo[]' has no call signatures.src/App.tsx(49,18): error TS2488: Type 'Todo[] | Dispatch<SetStateAction<Todo[]>>' must have a '[Symbol.iterator]()' method that returns an iterator.src/App.tsx(51,25): error TS7006: Parameter 'id' implicitly has an 'any' type.src/App.tsx(52,5): error TS2349: This expression is not callable.  Not all constituents of type 'Todo[] | Dispatch<SetStateAction<Todo[]>>' are callable.    Type 'Todo[]' has no call signatures.src/App.tsx(52,20): error TS2339: Property 'filter' does not exist on type 'Todo[] | Dispatch<SetStateAction<Todo[]>>'.  Property 'filter' does not exist on type 'Dispatch<SetStateAction<Todo[]>>'.src/App.tsx(53,8): error TS7006: Parameter 't' implicitly has an 'any' type.src/App.tsx(57,5): error TS2349: This expression is not callable.  Not all constituents of type 'Todo[] | Dispatch<SetStateAction<Todo[]>>' are callable.    Type 'Todo[]' has no call signatures.src/App.tsx(57,20): error TS2339: Property 'filter' does not exist on type 'Todo[] | Dispatch<SetStateAction<Todo[]>>'.  Property 'filter' does not exist on type 'Dispatch<SetStateAction<Todo[]>>'.src/App.tsx(58,8): error TS7006: Parameter 't' implicitly has an 'any' type.src/App.tsx(61,25): error TS7006: Parameter 'id' implicitly has an 'any' type.src/App.tsx(62,5): error TS2349: This expression is not callable.  Not all constituents of type 'Todo[] | Dispatch<SetStateAction<Todo[]>>' are callable.    Type 'Todo[]' has no call signatures.src/App.tsx(62,20): error TS2339: Property 'map' does not exist on type 'Todo[] | Dispatch<SetStateAction<Todo[]>>'.  Property 'map' does not exist on type 'Dispatch<SetStateAction<Todo[]>>'.src/App.tsx(62,25): error TS7006: Parameter 't' implicitly has an 'any' type.src/App.tsx(73,25): error TS2339: Property 'filter' does not exist on type 'Todo[] | Dispatch<SetStateAction<Todo[]>>'.  Property 'filter' does not exist on type 'Dispatch<SetStateAction<Todo[]>>'.src/App.tsx(74,6): error TS7006: Parameter 't' implicitly has an 'any' type.src/App.tsx(84,22): error TS2339: Property 'filter' does not exist on type 'Todo[] | Dispatch<SetStateAction<Todo[]>>'.  Property 'filter' does not exist on type 'Dispatch<SetStateAction<Todo[]>>'.src/App.tsx(85,6): error TS7006: Parameter 't' implicitly has an 'any' type.src/App.tsx(98,9): error TS2322: Type 'string | Dispatch<SetStateAction<string>>' is not assignable to type 'string'.  Type 'Dispatch<SetStateAction<string>>' is not assignable to type 'string'.src/App.tsx(99,9): error TS2322: Type 'string | Dispatch<SetStateAction<string>>' is not assignable to type '(value: string) => void'.  Type 'string' is not assignable to type '(value: string) => void'.

훅 이름과 todos 위에 마우스를 올려 봅니다.

마우스를 올린 곳보이는 글
훅 머리 useLocalStoragefunction useLocalStorage<T>(key: string, initial: T): (T | React.Dispatch<React.SetStateAction<T>>)[]
App의 todosconst todos: Todo[] | React.Dispatch<React.SetStateAction<Todo[]>>

훅이 돌려주는 것은 [value, setValue] 배열입니다. 타입이 다른 값을 섞은 배열은 원소 타입을 합친 배열로 넓혀집니다(TS 과목 배열과 튜플 2절의 ['라테', 4500]). 그래서 꺼낸 todos도 setTodos도 '배열이거나 set 함수'라, 배열로 쓰는 자리(todos.filter)와 부르는 자리(setTodos(…))마다 막힙니다. 칸은 T를 Todo[]로 바꿀 뿐입니다.

useState는 선언(@types/react)에 돌려주는 값이 '첫 자리 state · 둘째 자리 set 함수'인 튜플로 적혀 있습니다. 내 훅도 머리에 돌려주는 타입을 그 튜플로 적습니다. 배열과 튜플 2절에서 ['라테', 4500]의 자리마다 타입을 [string, number]로 정한 것과 같습니다. 둘째 자리는 state에 타입 1절에서 본 set 함수의 타입 Dispatch<SetStateAction<T>>⁠입니다. 둘 다 리액트가 내보내는 타입이라 type을 붙여 가져옵니다(ts-setup 예제의 TS1484).

src/useLocalStorage.ts
import {
  useEffect,
  useState,
  type Dispatch,
  type SetStateAction,
} from 'react';

load(): T처럼 머리의 ) 뒤에 적고, 끝 줄 return [value, setValue];⁠는 JS 판 그대로 둡니다.

src/useLocalStorage.ts
function useLocalStorage<T>(
  key: string,
  initial: T,
): [
  T,
  Dispatch<
    SetStateAction<T>
  >,
] {

마우스를 올린 글이 이렇게 바뀝니다. 훅 머리 글에는 이제 이 파일이 가져온 타입이라 React.가 붙지 않습니다(state에 타입 1절).

마우스를 올린 곳보이는 글
훅 머리 useLocalStoragefunction useLocalStorage<T>(key: string, initial: T): [T, Dispatch<SetStateAction<T>>]
App의 todosconst todos: Todo[]

다시 검사하면 넷이 남습니다.

검사 결과 오류 4개
src/App.tsx(20,20): error TS7006: Parameter 'list' implicitly has an 'any' type.src/App.tsx(43,22): error TS7006: Parameter 'text' implicitly has an 'any' type.src/App.tsx(51,25): error TS7006: Parameter 'id' implicitly has an 'any' type.src/App.tsx(61,25): error TS7006: Parameter 'id' implicitly has an 'any' type.

todos.filter((t) => …)⁠의 t는 이제 문맥으로 Todo라 사라졌고, 남은 넷은 매개변수입니다. getNextId의 list: Todo[], handleAdd의 text: string, handleDelete · handleToggle의 id: number를 적으면 0입니다(예제 둘째 · 넷째 · 다섯째 · 여섯째 조각).

예상과 다르면 그곳이 배울 곳입니다. ①을 골랐다면 매개변수도 칸에서 정해진다고 본 것입니다. 매개변수는 추론되지 않아 적어야 합니다(JS 코드에 타입 붙이기 하위 목표 2). ②를 골랐다면 훅이 돌려준 배열을 저절로 [값, set 함수] 짝으로 본 것입니다.

다 옮겨 검사가 0이 되면 "allowJs": true, 줄을 지웁니다. 남은 JS 파일이 없어 지워도 0이고, npm run build가 vite build까지 돌아 dist/를 만듭니다.

예제

끝 파일은 열하나입니다. 새 src/types.ts를 더했고, src/의 아홉은 이름이 .tsx · .ts로 바뀌었습니다. 글이 그대로인 것은 api.ts · Quote.tsx · public/quote.json입니다(접어 둠). main.tsx · tsconfig.app.json은 틀 그대로입니다. import 줄의 './TodoItem.jsx' 같은 경로는 그대로 두어도, 검사기와 Vite가 확장자만 다른 .tsx · .ts를 찾습니다.

파일 열 보기
src/types.ts
export type Todo = {
  id: number;
  text: string;
  done: boolean;
};
src/TodoItem.tsx
import type {
  Todo,
} from './types.ts';

interface TodoItemProps {
  todo: Todo;
  onToggle: (
    id: number,
  ) => void;
  onDelete: (
    id: number,
  ) => void;
}

function TodoItem({
  todo,
  onToggle,
  onDelete,
}: TodoItemProps) {
  return (
    <li
      className={
        todo.done ? 'done' : ''
      }
    >
      <input
        type="checkbox"
        checked={todo.done}
        onChange={() =>
          onToggle(todo.id)
        }
      />
      <span className="text">
        {todo.text}
      </span>
      <button
        className="delete"
        onClick={() =>
          onDelete(todo.id)
        }
      >
        ×
      </button>
    </li>
  );
}

export default TodoItem;
src/TodoList.tsx
import TodoItem from
  './TodoItem.jsx';
import type {
  Todo,
} from './types.ts';

interface TodoListProps {
  todos: Todo[];
  onToggle: (
    id: number,
  ) => void;
  onDelete: (
    id: number,
  ) => void;
}

function TodoList({
  todos,
  onToggle,
  onDelete,
}: TodoListProps) {
  if (todos.length === 0) {
    return (
      <p className="empty">
        할 일이 없습니다.
      </p>
    );
  }
  return (
    <ul id="todo-list">
      {todos.map((todo) => (
        <TodoItem
          key={todo.id}
          todo={todo}
          onToggle={onToggle}
          onDelete={onDelete}
        />
      ))}
    </ul>
  );
}

export default TodoList;
src/TodoFilters.tsx
const choices = [
  ['all', '전체'],
  ['active', '진행 중'],
  ['done', '완료'],
];

interface TodoFiltersProps {
  filter: string;
  onChange: (
    value: string,
  ) => void;
}

function TodoFilters({
  filter,
  onChange,
}: TodoFiltersProps) {
  const buttons = choices.map(
    ([value, label]) => (
      <button
        key={value}
        className={
          value === filter
            ? 'active'
            : ''
        }
        onClick={() =>
          onChange(value)
        }
      >
        {label}
      </button>
    ),
  );
  return (
    <div className="filters">
      {buttons}
    </div>
  );
}

export default TodoFilters;
src/TodoFooter.tsx
interface TodoFooterProps {
  total: number;
  left: number;
  onClearDone: () => void;
}

function TodoFooter({
  total,
  left,
  onClearDone,
}: TodoFooterProps) {
  return (
    <footer className="footer">
      <p className="count">
        전체 {total}개
        중 {left}개 남음
      </p>
      <button
        className="clear"
        onClick={onClearDone}
      >
        완료한 일 지우기
      </button>
    </footer>
  );
}

export default TodoFooter;
src/TodoForm.tsx
import {
  useRef,
  useState,
  type ChangeEvent,
  type SubmitEvent,
} from 'react';

type InputChangeEvent =
  ChangeEvent<HTMLInputElement>;
type FormSubmitEvent =
  SubmitEvent<HTMLFormElement>;

interface TodoFormProps {
  onAdd: (text: string) => void;
}

function TodoForm({
  onAdd,
}: TodoFormProps) {
  // 4. state 자리 정하기
  const [text, setText] =
    useState('');
  const inputRef =
    useRef<HTMLInputElement>(
      null,
    );
  function handleChange(
    e: InputChangeEvent,
  ) {
    setText(e.target.value);
  }
  // 5. 바꾸는 일은 위로 알리기
  function handleSubmit(
    e: FormSubmitEvent,
  ) {
    e.preventDefault();
    if (inputRef.current) {
      inputRef.current.focus();
    }
    const value = text.trim();
    if (value === '') return;
    onAdd(value);
    setText('');
  }
  return (
    <form
      id="todo-form"
      onSubmit={handleSubmit}
    >
      <label
        htmlFor="todo-input"
      >
        할 일
      </label>
      <input
        ref={inputRef}
        id="todo-input"
        value={text}
        onChange={handleChange}
      />
      <button>추가</button>
    </form>
  );
}

export default TodoForm;
src/useLocalStorage.ts
import {
  useEffect,
  useState,
  type Dispatch,
  type SetStateAction,
} from 'react';

// 2. use로 시작하는 함수로 옮기기
function useLocalStorage<T>(
  key: string,
  initial: T,
): [
  T,
  Dispatch<
    SetStateAction<T>
  >,
] {
  function load(): T {
    const raw = localStorage
      .getItem(key);
    if (raw === null) {
      return initial;
    }
    const saved =
      JSON.parse(raw);
    return saved ?? initial;
  }
  const [value, setValue] =
    useState(load);
  useEffect(() => {
    localStorage.setItem(
      key,
      JSON.stringify(value),
    );
  }, [key, value]);
  // 3. 필요한 값만 돌려주기
  return [value, setValue];
}

export default useLocalStorage;
src/api.ts
async function getQuote() {
  const res = await fetch(
    '/quote.json',
  );
  if (!res.ok) {
    throw new Error(
      `HTTP ${res.status}`,
    );
  }
  const data = await res.json();
  return data.quote;
}

export default getQuote;
src/Quote.tsx
import {
  useEffect,
  useState,
} from 'react';
import getQuote from
  './api.js';

function Quote() {
  const [quote, setQuote] =
    useState('오늘도 한 걸음씩.');
  useEffect(() => {
    let ignore = false;
    // 1. 받기 시작
    async function loadQuote() {
      try {
        const text =
          await getQuote();
        // 2. 결과를 state로
        if (!ignore) {
          setQuote(text);
        }
      } catch {
        // 오류면 처음 글 그대로
      }
    }
    loadQuote();
    // 3. 늦게 온 옛 결과 버리기
    return () => {
      ignore = true;
    };
  }, []);
  return (
    <p className="quote">
      {quote}
    </p>
  );
}

export default Quote;
public/quote.json
{
  "quote": "시작이 반이다."
}

src/App.tsx는 열 조각이고, 바뀐 곳은 둘째 ~ 여섯째 조각(Todo 가져오기 · 칸 · 매개변수 넷)입니다. 첫째 ~ 셋째 조각은 접어 둡니다.

첫째 ~ 셋째 조각 보기

첫 조각은 그대로입니다.

src/App.tsx
import {
  useEffect,
} from 'react';
import useLocalStorage from
  './useLocalStorage.js';
import TodoForm from
  './TodoForm.jsx';
import TodoFilters from
  './TodoFilters.jsx';
import TodoList from
  './TodoList.jsx';
import TodoFooter from
  './TodoFooter.jsx';
import Quote from
  './Quote.jsx';

앞 코드에 이어 씁니다.

src/App.tsx
import type {
  Todo,
} from './types.ts';

function getNextId(
  list: Todo[],
) {
  let max = 0;
  for (const t of list) {
    if (t.id > max) {
      max = t.id;
    }
  }
  return max + 1;
}

앞 코드에 이어 씁니다.

src/App.tsx
function App() {
  // 4. state 자리 정하기
  const [todos, setTodos] =
    useLocalStorage<Todo[]>(
      'todos',
      [],
    );
  const [filter, setFilter] =
    useLocalStorage(
      'filter',
      'all',
    );

앞 코드에 이어 씁니다.

src/App.tsx
  // 5. 바꾸는 일은 위로 알리기
  function handleAdd(
    text: string,
  ) {
    const todo = {
      id: getNextId(todos),
      text,
      done: false,
    };
    setTodos([...todos, todo]);
  }

앞 코드에 이어 씁니다.

src/App.tsx
  function handleDelete(
    id: number,
  ) {
    setTodos(todos.filter(
      (t) => t.id !== id,
    ));
  }
  function handleClearDone() {
    setTodos(todos.filter(
      (t) => !t.done,
    ));
  }

앞 코드에 이어 씁니다.

src/App.tsx
  function handleToggle(
    id: number,
  ) {
    setTodos(todos.map((t) => {
      if (t.id === id) {
        return {
          ...t,
          done: !t.done,
        };
      }
      return t;
    }));
  }

앞 코드에 이어 씁니다. 일곱째 조각은 그대로입니다.

src/App.tsx
  // 3. 가장 작은 state 찾기
  const visible = todos.filter(
    (t) => {
      if (filter === 'active') {
        return !t.done;
      }
      if (filter === 'done') {
        return t.done;
      }
      return true;
    },
  );
  const left = todos.filter(
    (t) => !t.done,
  ).length;
여덟째 조각 보기

앞 코드에 이어 씁니다. 여덟째 조각도 그대로입니다.

src/App.tsx
  useEffect(() => {
    document.title =
      `할 일 ${left}개`;
  }, [left]);

앞 코드에 이어 씁니다. 아홉째 조각도 그대로입니다.

src/App.tsx
  return (
    <main className="app">
      <h1>오늘 할 일</h1>
      <TodoForm
        onAdd={handleAdd}
      />
      <TodoFilters
        filter={filter}
        onChange={setFilter}
      />
      <TodoList
        todos={visible}
        onToggle={handleToggle}
        onDelete={handleDelete}
      />

끝 조각도 그대로라 화면과 함께 접어 둡니다. 화면은 단원 8 끝 판과 같습니다.

끝 조각 · 화면 · src/App.tsx 전체 보기

앞 코드에 이어 씁니다. 코드 아래 상자는 처음 연 브라우저에서 우유 사기 · 산책을 더하고 진행 중을 누른 뒤 화면입니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다.

src/App.tsx
      <TodoFooter
        total={todos.length}
        left={left}
        onClearDone={
          handleClearDone
        }
      />
      <Quote />
    </main>
  );
}

export default App;
<main class="app"><h1>오늘 할 일</h1><form id="todo-form"><label for="todo-input">할 일</label><input id="todo-input" value=""><button>추가</button></form><div class="filters"><button class="">전체</button><button class="active">진행 중</button><button class="">완료</button></div><ul id="todo-list"><li class=""><input type="checkbox"><span class="text">우유 사기</span><button class="delete">×</button></li><li class=""><input type="checkbox"><span class="text">산책</span><button class="delete">×</button></li></ul><footer class="footer"><p class="count">전체 2개 중 2개 남음</p><button class="clear">완료한 일 지우기</button></footer><p class="quote">시작이 반이다.</p></main>
결과 화면

그 아래는 src/App.tsx 전체입니다.

src/App.tsx
import {
  useEffect,
} from 'react';
import useLocalStorage from
  './useLocalStorage.js';
import TodoForm from
  './TodoForm.jsx';
import TodoFilters from
  './TodoFilters.jsx';
import TodoList from
  './TodoList.jsx';
import TodoFooter from
  './TodoFooter.jsx';
import Quote from
  './Quote.jsx';
import type {
  Todo,
} from './types.ts';

function getNextId(
  list: Todo[],
) {
  let max = 0;
  for (const t of list) {
    if (t.id > max) {
      max = t.id;
    }
  }
  return max + 1;
}

function App() {
  // 4. state 자리 정하기
  const [todos, setTodos] =
    useLocalStorage<Todo[]>(
      'todos',
      [],
    );
  const [filter, setFilter] =
    useLocalStorage(
      'filter',
      'all',
    );
  // 5. 바꾸는 일은 위로 알리기
  function handleAdd(
    text: string,
  ) {
    const todo = {
      id: getNextId(todos),
      text,
      done: false,
    };
    setTodos([...todos, todo]);
  }
  function handleDelete(
    id: number,
  ) {
    setTodos(todos.filter(
      (t) => t.id !== id,
    ));
  }
  function handleClearDone() {
    setTodos(todos.filter(
      (t) => !t.done,
    ));
  }
  function handleToggle(
    id: number,
  ) {
    setTodos(todos.map((t) => {
      if (t.id === id) {
        return {
          ...t,
          done: !t.done,
        };
      }
      return t;
    }));
  }
  // 3. 가장 작은 state 찾기
  const visible = todos.filter(
    (t) => {
      if (filter === 'active') {
        return !t.done;
      }
      if (filter === 'done') {
        return t.done;
      }
      return true;
    },
  );
  const left = todos.filter(
    (t) => !t.done,
  ).length;
  useEffect(() => {
    document.title =
      `할 일 ${left}개`;
  }, [left]);
  return (
    <main className="app">
      <h1>오늘 할 일</h1>
      <TodoForm
        onAdd={handleAdd}
      />
      <TodoFilters
        filter={filter}
        onChange={setFilter}
      />
      <TodoList
        todos={visible}
        onToggle={handleToggle}
        onDelete={handleDelete}
      />
      <TodoFooter
        total={todos.length}
        left={left}
        onClearDone={
          handleClearDone
        }
      />
      <Quote />
    </main>
  );
}

export default App;

자주 틀리는 곳

  • 모든 파일 이름을 한꺼번에 바꿈. npx tsc -b가 모두 28건(TS7031 열둘 · TS7006 열넷 · TS2345 하나 · TS18047 하나)을 한꺼번에 냅니다. 가져다 쓰이는 쪽부터 한 파일씩 바꿉니다(TS 과목 마무리 3절과 같은 길).
  • raw! · raw as string으로 TS2345를 지움. 검사는 0이지만, 검사기에게 'null이 아니다'라고 말했을 뿐입니다(as는 검사기에게 하는 말). if로 좁힙니다.
  • getItem(key) ?? '[]'로 null을 메움. 검사는 0이지만 같은 훅을 쓰는 filter의 처음 값도 []가 되어, 처음 연 브라우저에서 거르기 단추 셋 가운데 눌린 것(active)이 없습니다. 검사기는 실행 때의 값을 보지 않습니다.
  • 훅 머리에 돌려주는 타입을 적지 않음. 꺼낸 두 이름이 '배열이거나 set 함수'로 넓어집니다. 머리에 튜플을 적습니다(4절).
  • 맨 위 폴더의 npx tsc --noEmit이 조용해서 다 옮겼다고 봄. react-ts 틀에서는 오류가 있어도 조용합니다(ts-setup 4절). npx tsc -b나 npm run build로 셉니다.

확인 문제

1. 이 레슨의 차례대로 옮길 때, TodoList.jsx를 .tsx로 바꾸기 전에 먼저 바꿔 두는 파일은 무엇일까요?

  • ① App.jsx
  • ② useLocalStorage.js
  • ③ TodoItem.jsx
정답

③입니다. TodoList가 TodoItem을 가져다 쓰니, 가져다 쓰이는 TodoItem을 먼저 바꿉니다. 그래야 TodoList를 바꿀 때 <TodoItem … />에 넘기는 값이 TodoItemProps와 맞춰집니다.

  • ① App은 TodoList를 가져다 쓰는 쪽이라 맨 끝입니다.
  • ② useLocalStorage와 TodoList는 서로 가져다 쓰지 않아, 둘 사이에는 먼저 할 차례가 없습니다.

2. 2절 차례대로 TodoFilters.tsx까지 0으로 만든 뒤, TodoFooter.jsx의 이름만 TodoFooter.tsx로 바꾸고 npx tsc -b를 쳤습니다. 무엇이 나올까요?

  • ① TS7031 셋 — total · left · onClearDone
  • ② TS7016 하나 — 가져오는 App.jsx가 아직 JS라서
  • ③ 아무것도 찍지 않는다 — allowJs를 켰으니
정답

①입니다. 구조 분해한 props 셋의 타입이 정해지지 않았습니다. interface TodoFooterProps⁠를 적으면 0입니다.

  • ② TS7016은 allowJs 없이 .tsx가 .jsx를 가져올 때 났습니다. 여기서는 켜져 있고, 가져오는 App.jsx 쪽에는 오류가 나지 않습니다.
  • ③ allowJs는 JS 파일을 프로젝트에 받을 뿐, .tsx로 바꾼 파일의 검사를 줄이지 않습니다.

3. JS 판 훅에 <T> · key: string · initial: T · load(): T만 적고, if (raw === null) 세 줄은 넣지 않았습니다. return saved ?? initial;⁠은 그대로입니다. npx tsc -b의 결과는 무엇일까요?

  • ① 0 — ?? initial이 null을 처음 값으로 바꾼다
  • ② JSON.parse(raw)의 raw에 TS2345 하나
  • ③ return saved ?? initial; 줄에 TS2322 하나
정답

②입니다. getItem이 돌려준 raw는 string | null이고 JSON.parse는 string만 받아, 15번 줄 18번째 칸의 raw에서 막힙니다.

  • ① 실행 때는 그렇지만, 검사기는 JSON.parse의 선언에 string | null을 넘긴 것을 짚습니다.
  • ③ JSON.parse가 돌려준 saved는 any라 T 자리에 그대로 들어갑니다.

컴퓨터에서 해 보기(선택) — 점수에 들지 않습니다. 폰으로만 보고 있다면 건너뛰세요.

  1. 끝 판의 TodoList.tsx 34번 줄 todo={todo}를 todo={todo.text}로 바꿉니다.
  2. npx tsc -b를 쳐서 오류가 어느 파일 몇 번 줄에 나는지 보고, TodoItemProps의 todo: Todo와 견줍니다.
  3. 다 보면 34번 줄을 todo={todo}로 되돌립니다.

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

리액트 목차로