이 레슨은 할 일 목록 reducer의 action을 판별 유니언으로 적어 case마다 action이 좁혀지는 것을 보고, dispatch에 모르는 type이나 빠진 값을 보내면 어떻게 되는지 봅니다. 돌려주는 타입으로 빠진 case를 짚고, createContext의 첫 값 null은 커스텀 훅 하나에서 걸러 Todo[]로 씁니다.
ts-setup에서 만든 todo-ts에서 씁니다. 화면은 npm run dev로, 검사는 npm run build로 보고, 결과 상자는 ts-setup 4절처럼 오류를 한 줄 꼴로 적습니다. TS 과목의 판별 유니언 · 빠짐없이 — never로 갈래 검사 · null·undefined 거르기를 마쳤다고 보고 씁니다.
1action을 판별 유니언으로 — case마다 좁혀진다
할 일 화면 — reducer와 Context로의 action 가운데 더하기 { type: 'added', id, text }와 지우기 { type: 'deleted', id }의 모양부터 타입으로 적습니다. src/todos.ts를 새로 만듭니다.
export type Todo = {
id: number;
text: string;
done: boolean;
};
interface Added {
type: 'added';
id: number;
text: string;
}
interface Deleted {
type: 'deleted';
id: number;
}갈래 속성 type에는 값 하나짜리 리터럴을 적었고, 둘을 묶은 Action이 판별 유니언입니다. reducer는 action을 Action으로 받고, 돌려주는 타입은 Todo[]로 적습니다.
앞 코드에 이어 씁니다.
type Action = Added | Deleted;
export function todosReducer(
todos: Todo[],
action: Action,
): Todo[] {
switch (action.type) {
case 'added':
return [
...todos,
{
id: action.id,
text: action.text,
done: false,
},앞 코드에 이어 씁니다.
];
case 'deleted':
return todos.filter(
(t) =>
t.id !== action.id,
);
}
}case 'added':도 action.type === 'added'와 같은 확인이라, 검사기는 그 아래 줄에서 action을 Added로 좁힙니다(판별 유니언 3절). 마우스를 올려 본 타입을 표로 적습니다.
| 줄 | 이름 | 지금 타입 |
|---|---|---|
| 22 | action | Action |
| 27 ~ 28 | action | Added |
| 35 | action | Deleted |
그래서 added 갈래는 action.text를 읽고, deleted 갈래는 Deleted에 있는 id만 읽습니다.
dispatch에 모르는 type을 보내면
src/App.tsx는 먼저 메모 앱에 옮겨 두고, 모두 지운 뒤 아래 판을 씁니다. 단추를 누르면 할 일을 하나 더하는데, type을 todo-reducer 자주 틀리는 곳처럼 'add'로 잘못 썼습니다.
import {
useReducer,
} from 'react';
import {
todosReducer,
} from './todos.ts';
let nextId = 1;
function App() {
const [todos, dispatch] =
useReducer(
todosReducer,
[],
);앞 코드에 이어 씁니다.
function handleAdd() {
dispatch({
type: 'add',
id: nextId++,
text: '산책하기',
});
}
return (
<button onClick={handleAdd}>
할 일 {todos.length}개
</button>
);
}
export default App;src/App.tsx(18,7): error TS2322: Type '"add"' is not assignable to type '"added" | "deleted"'.18번 줄의 'add'를 'added' | 'deleted' 자리에 넣을 수 없다는 뜻입니다. 꺾쇠를 비워도 useReducer의 타입 칸이 todosReducer의 타입으로 채워져, dispatch는 Action만 받습니다. 마우스를 올려 보면 이렇습니다.
| 마우스를 올린 곳 | 보이는 글 |
|---|---|
todos | const todos: Todo[] |
17번 줄 dispatch | const dispatch: (action: Action) => void |
빈 배열도 state에 타입 2절의 never[]가 아니라 Todo[]입니다. JS 판에서 누른 순간 모르는 action: add로 드러나던 실수를, 이제는 누르기 전에 쓰는 자리에서 짚습니다. text를 빠뜨린 더하기도 Added 모양이 아니라 dispatch를 부르는 자리에서 막힙니다.
18번 줄을 type: 'added',로 고치면 검사를 지나고, 단추를 두 번 누르면 할 일 2개가 됩니다(아래 '코드와 결과 보기').
코드와 결과 보기
18번 줄을 고친 판입니다. 코드 아래 두 상자는 처음 화면과 단추를 두 번 누른 뒤의 화면입니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다.
import {
useReducer,
} from 'react';
import {
todosReducer,
} from './todos.ts';
let nextId = 1;
function App() {
const [todos, dispatch] =
useReducer(
todosReducer,
[],
);앞 코드에 이어 씁니다.
function handleAdd() {
dispatch({
type: 'added',
id: nextId++,
text: '산책하기',
});
}앞 코드에 이어 씁니다.
return (
<button
onClick={handleAdd}
>
할 일 {todos.length}개
</button>
);
}
export default App;<button>할 일 0개</button><button>할 일 2개</button>2빠진 case — 돌려주는 타입이 짚는다
todo-reducer처럼 완료 표시 toggled를 더합니다. Added 아래에 Toggled를 두고, 갈래가 셋이라 Action은 갈래마다 한 줄씩 씁니다.
interface Toggled {
type: 'toggled';
id: number;
}
type Action =
| Added
| Toggled
| Deleted;case 'toggled':를 아직 쓰지 않고 npm run build를 치면 막힙니다(아래 '코드와 결과 보기').
코드와 결과 보기
src/todos.ts 전체입니다. case 'toggled':가 아직 없습니다.
export type Todo = {
id: number;
text: string;
done: boolean;
};
interface Added {
type: 'added';
id: number;
text: string;
}
interface Toggled {
type: 'toggled';
id: number;
}
interface Deleted {
type: 'deleted';
id: number;
}
type Action =
| Added
| Toggled
| Deleted;
export function todosReducer(
todos: Todo[],
action: Action,
): Todo[] {
switch (action.type) {
case 'added':
return [
...todos,
{
id: action.id,
text: action.text,
done: false,
},
];
case 'deleted':
return todos.filter(
(t) =>
t.id !== action.id,
);
}
}src/App.tsx는 1절에서 고친 판 그대로입니다.
import {
useReducer,
} from 'react';
import {
todosReducer,
} from './todos.ts';
let nextId = 1;
function App() {
const [todos, dispatch] =
useReducer(
todosReducer,
[],
);앞 코드에 이어 씁니다.
function handleAdd() {
dispatch({
type: 'added',
id: nextId++,
text: '산책하기',
});
}앞 코드에 이어 씁니다.
return (
<button
onClick={handleAdd}
>
할 일 {todos.length}개
</button>
);
}
export default App;src/todos.ts(28,4): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.오류는 TS2366으로, 28번 줄의 돌려주는 타입 Todo[]를 짚습니다. '함수 끝에 return이 없는데 돌려주는 타입에 undefined가 없다'는 뜻입니다. toggled action은 어느 case에도 걸리지 않고 끝으로 나가 undefined를 돌려주게 됩니다.
todo-reducer의 toggled 갈래를 case 'deleted': 위에 넣으면 오류가 사라집니다(예제 todos.ts). JS 판의 default: throw는 옮기지 않았습니다(아래 'Todo[]를 빼거나 default를 두면').
Todo[]를 빼거나 default를 두면
돌려주는 타입 Todo[]를 지우면 같은 어긋남이 App.tsx에서 useReducer에 넘긴 todosReducer 자리의 세 줄짜리 TS2345(Todo[] | undefined를 Todo[] 자리에 넣을 수 없다)로 납니다. 고칠 곳은 todos.ts인데 오류는 App.tsx에 나는 셈입니다.
toggled 갈래를 빠뜨린 채 default에서 던지면 toggled도 default로 가, npm run build가 조용히 지납니다. 빠진 것은 그 action을 보낸 순간 하얀 화면으로 알게 됩니다. 갈래를 다 채운 뒤 JS 판 그대로 action.type을 오류 글에 붙이면, 남은 갈래가 없는 default의 action은 never라 그 줄이 TS2339(on type 'never')로 막힙니다. default에서 빠진 갈래를 짚게 하는 꼴은 TS 과목 빠짐없이 2절입니다.
3context에 타입 — null은 훅 하나에서 거른다
todo-reducer는 목록을 내려 보내는 TodosContext의 기본값을 null로 두었습니다. 타입 칸에 목록의 타입과 null을 함께 적습니다. src/todosContext.ts를 새로 만듭니다(가져오기는 아래 접기 판).
export const TodosContext =
createContext<Todo[] | null>(
null,
);useContext(TodosContext)로 꺼낸 값은 Todo[] | null입니다. 그대로 todos.map(…)을 쓰면 TS18047(null일 수 있다)로 막힙니다(아래 '코드와 결과 보기'). 위에 provider가 있는지는 그릴 때 정해지는 일이라 검사기는 모릅니다.
코드와 결과 보기
훅 없이 useContext로 바로 꺼낸 판입니다. src/todos.ts는 예제 판(toggled 갈래를 넣은 판)입니다.
export type Todo = {
id: number;
text: string;
done: boolean;
};
interface Added {
type: 'added';
id: number;
text: string;
}
interface Toggled {
type: 'toggled';
id: number;
}
interface Deleted {
type: 'deleted';
id: number;
}
type Action =
| Added
| Toggled
| Deleted;
export function todosReducer(
todos: Todo[],
action: Action,
): Todo[] {
switch (action.type) {
case 'added':
return [
...todos,
{
id: action.id,
text: action.text,
done: false,
},
];
case 'toggled':
return todos.map((t) => {
if (
t.id === action.id
) {
return {
...t,
done: !t.done,
};
}
return t;
});
case 'deleted':
return todos.filter(
(t) =>
t.id !== action.id,
);
}
}import {
createContext,
} from 'react';
import type {
Todo,
} from './todos.ts';
export const TodosContext =
createContext<Todo[] | null>(
null,
);import {
useContext,
} from 'react';
import {
TodosContext,
} from './todosContext.ts';
function TodoList() {
const todos = useContext(
TodosContext,
);
return (
<ul>
{todos.map((t) => (
<li key={t.id}>
{t.text}
</li>
))}
</ul>
);
}
export default TodoList;src/App.tsx는 빈 목록을 provider로 내려 TodoList를 그립니다.
import TodoList from
'./TodoList.tsx';
import {
TodosContext,
} from './todosContext.ts';
function App() {
return (
<TodosContext value={[]}>
<TodoList />
</TodosContext>
);
}
export default App;src/TodoList.tsx(14,8): error TS18047: 'todos' is possibly 'null'.꺼내는 곳마다 ?. · !를 붙이지 않고, 꺼내는 일을 커스텀 훅 하나에 담아 거기서 한 번 확인합니다(커스텀 훅). 가져오기에 useContext를 더하고, 같은 파일 끝에 씁니다.
export function useTodos() {
const todos = useContext(
TodosContext,
);
if (todos === null) {
throw new Error(
'TodosContext 밖입니다',
);
}
return todos;
}if를 지난 todos는 Todo[]로 좁혀지고, useTodos가 돌려주는 타입도 Todo[]입니다(마우스를 올리면 function useTodos(): Todo[]). 쓰는 쪽은 const todos = useTodos(); 한 줄이면 됩니다. react.dev(Using TypeScript)도 훅에서 실행 때 값을 확인해 없으면 오류를 던지는 이 꼴을 권합니다.
예제
끝 파일 넷을 접어 둡니다. TodoList.tsx는 useTodos()로 꺼낸 목록을 그리고, App.tsx는 1절 판의 단추와 TodoList를 TodosContext로 감쌉니다.
src/ 파일 넷 보기
export type Todo = {
id: number;
text: string;
done: boolean;
};
interface Added {
type: 'added';
id: number;
text: string;
}
interface Toggled {
type: 'toggled';
id: number;
}
interface Deleted {
type: 'deleted';
id: number;
}
type Action =
| Added
| Toggled
| Deleted;
export function todosReducer(
todos: Todo[],
action: Action,
): Todo[] {
switch (action.type) {
case 'added':
return [
...todos,
{
id: action.id,
text: action.text,
done: false,
},
];
case 'toggled':
return todos.map((t) => {
if (
t.id === action.id
) {
return {
...t,
done: !t.done,
};
}
return t;
});
case 'deleted':
return todos.filter(
(t) =>
t.id !== action.id,
);
}
}import {
createContext,
useContext,
} from 'react';
import type {
Todo,
} from './todos.ts';
export const TodosContext =
createContext<Todo[] | null>(
null,
);
export function useTodos() {
const todos = useContext(
TodosContext,
);
if (todos === null) {
throw new Error(
'TodosContext 밖입니다',
);
}
return todos;
}import {
useTodos,
} from './todosContext.ts';
function TodoList() {
const todos = useTodos();
return (
<ul>
{todos.map((t) => (
<li key={t.id}>
{t.text}
</li>
))}
</ul>
);
}
export default TodoList;src/App.tsx입니다. 코드 아래 두 상자는 처음 화면과 단추를 한 번 누른 뒤의 화면입니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다.
import {
useReducer,
} from 'react';
import {
todosReducer,
} from './todos.ts';
import {
TodosContext,
} from './todosContext.ts';
import TodoList from
'./TodoList.tsx';
let nextId = 1;앞 코드에 이어 씁니다.
function App() {
const [todos, dispatch] =
useReducer(
todosReducer,
[],
);
function handleAdd() {
dispatch({
type: 'added',
id: nextId++,
text: '산책하기',
});
}앞 코드에 이어 씁니다.
return (
<TodosContext
value={todos}
>
<TodoList />
<button
onClick={handleAdd}
>
더하기
</button>
</TodosContext>
);
}
export default App;<ul></ul><button>더하기</button><ul><li>산책하기</li></ul><button>더하기</button>맞혀 봅니다. App의 return을 아래처럼 바꿔 <TodoList />를 TodosContext 밖으로 옮기면 npm run build와 화면은 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
return (
<>
<TodoList />
<TodosContext
value={todos}
>
<button
onClick={handleAdd}
>
더하기
</button>
</TodosContext>
</>
);- ①
npm run build가 막는다 — 검사기가 provider 밖인 것을 짚는다 - ② 검사는 지나고, 첫 화면부터 하얘진다 —
useTodos가 오류를 던진다 - ③ 검사도 지나고 단추만 보인다 —
TodoList가 빈 목록을 그린다
결과 보기
②입니다. 코드 아래 두 상자는 쪽을 연 뒤의 화면과 콘솔입니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다.
import {
useReducer,
} from 'react';
import {
todosReducer,
} from './todos.ts';
import {
TodosContext,
} from './todosContext.ts';
import TodoList from
'./TodoList.tsx';
let nextId = 1;앞 코드에 이어 씁니다.
function App() {
const [todos, dispatch] =
useReducer(
todosReducer,
[],
);
function handleAdd() {
dispatch({
type: 'added',
id: nextId++,
text: '산책하기',
});
}앞 코드에 이어 씁니다.
return (
<>
<TodoList />
<TodosContext
value={todos}
>
<button
onClick={handleAdd}
>
더하기
</button>
</TodosContext>
</>
);앞 코드에 이어 씁니다.
}
export default App;[잡히지 않은 오류] TodosContext 밖입니다
[경고] An error occurred in the <TodoList> component.
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react.dev/link/error-boundaries to learn more about error boundaries.
npm run build는 지납니다. TodoList는 위로 올라가도 provider를 만나지 않아 기본값 null을 읽고(Context 레슨 4절), useTodos의 if가 오류를 던집니다. 렌더 중에 난 오류라 화면이 통째로 빕니다. 검사기는 그 값이 실행 때 null인지 보지 않고 타입만 봅니다.
예상과 다르면 그곳이 배울 곳입니다. ①을 골랐다면 검사기가 나무의 짜임까지 본다고 생각한 것입니다. ③을 골랐다면 JS 판처럼 기본값을 읽고 조용히 넘어간다고 본 것입니다 — 그 조용함을 막으려고 훅에서 던집니다.
다 보면 src/todos.ts · src/todosContext.ts · src/TodoList.tsx를 지우고, App.tsx를 메모 앱 판으로 되돌립니다.
자주 틀리는 곳
틀린 생각: state 타입은 useReducer<Todo[]>(…)처럼 꺾쇠에 적는다.
react.dev(Using TypeScript)에는 꺾쇠에 state 타입 하나를 적는 판(useReducer<State>(…))도 있지만, 이 템플릿의 @types/react 19.3.0에서는 TS2558(타입 인자가 둘이어야 하는데 하나)로 막힙니다.
맞는 규칙: 꺾쇠는 비우고 reducer의 매개변수와 돌려주는 타입에 적습니다. useReducer가 거기서 칸을 채웁니다.
틀린 생각: context 기본값이 null이라 꺼내는 곳마다 todos?.map · todos!.map을 붙인다.
?.는 null이면 빈 목록을 그려 provider를 빠뜨린 것을 묻고, !는 검사만 꺼 null에 점을 찍는 빨간 줄(Cannot read properties of null)을 냅니다(이벤트 · ref에 타입 자주 틀리는 곳).
맞는 규칙: 확인은 useTodos 하나에서 합니다.
틀린 생각: action의 type은 string으로 적으면 된다.
type: string이면 case 'added':를 지나도 두 갈래가 다 남아 좁혀지지 않습니다. action.text 줄이 TS2339(Action에 text가 없다)로, 돌려주는 타입 자리가 TS2366으로 막힙니다.
맞는 규칙: 갈래 속성은 갈래마다 값 하나짜리 리터럴로 적습니다(리터럴 유니언으로 값 고르기).
확인 문제
1. 1절의 고친 판에서 handleAdd의 text: '산책하기', 줄을 빠뜨렸습니다. npm run build는 어떻게 될까요?
- ① 검사를 지난다 — 누르면 글이 빈 할 일이 더해진다
- ②
dispatch줄에서 막힌다 —Added에 있어야 할text가 없다 - ③
todos.ts의text: action.text줄에서 막힌다 — 읽을text가 없다
정답
②입니다. dispatch가 받는 것은 Action이라, type이 'added'인 객체는 Added의 속성을 다 갖춰야 합니다. 그래서 넘기는 자리인 17번 줄 dispatch({의 {에서 TS2345가 나고, 둘째 줄이 Property 'text' is missing(text가 빠졌다)입니다.
- ① 빠진 값도 모르는
type처럼 누르기 전에 짚습니다. - ③
todos.ts는Added에text가 있다고 믿고 읽을 뿐입니다. 어긋난 곳은 넘기는 쪽입니다.
2. 예제 todos.ts의 case 'toggled': 갈래에서 고를 할 일을 id 대신 글로 찾게 바꿨습니다. npm run build는 어떻게 될까요?
case 'toggled':
return todos.map((t) => {
if (
t.text === action.text
) {- ① 검사를 지난다 —
Action의 한 갈래에text가 있다 - ②
t.text자리에서 막힌다 —Todo에text가 없다 - ③
action.text자리에서 막힌다 — 이 갈래의action은Toggled다
정답
③입니다. case 'toggled': 아래에서 action은 Toggled로 좁혀져 있고, Toggled에는 text가 없습니다. 42번 줄 action.text의 text에서 TS2339(Toggled에 text가 없다)가 납니다.
- ① 좁혀진 갈래에서는 그 갈래의 속성만 씁니다.
Added의text는added갈래에서만 읽습니다. - ②
t는Todo라text가 있습니다.
3. 3절의 useTodos를 아래처럼 if 없이 썼습니다. 이 훅으로 꺼낸 목록에 todos.map(…)을 쓰는 TodoList는 npm run build에서 어떻게 될까요?
export function useTodos() {
return useContext(
TodosContext,
);
}- ①
todos.map줄이TS18047로 막힌다 — 돌려주는 타입이Todo[] | null이다 - ② 검사를 지난다 — 값은
App이 provider로 넣어 준 목록이다 - ③ 검사를 지난다 — 훅으로 빼면
null이 걸러진다
정답
①입니다. 거르는 if가 없으니 훅이 돌려주는 타입은 useContext가 준 Todo[] | null 그대로입니다. TodoList의 todos.map 줄에서 3절 '코드와 결과 보기'와 같은 TS18047이 납니다.
- ②
App이 넣어 준 것은 실행 때의 값입니다. 검사기는 타입만 봅니다. - ③ 걸러지는 것은 훅 안의
if덕분입니다. 함수로 빼기만 해서는 타입이 바뀌지 않습니다.
컴퓨터에서 해 보기(선택) — 점수에 들지 않습니다. 폰으로만 보고 있다면 건너뛰세요.
- 1절 판으로
src/todos.ts를 씁니다. - 2절처럼
Toggled를 더하고case는 쓰지 않은 채npm run build를 칩니다.TS2366이 돌려주는 타입 자리를 짚습니다. - 예제의
toggled갈래를 넣고 다시 치면 지납니다. - 다 보면
todos.ts를 지웁니다.