TypeScript โปรเจกต์: React แอปเล็ก
แอปจัดการ task — typed ตั้งแต่ props ถึง API รวมทุกอย่างจากซีรีส์
setup
npm create vite@latest task-app -- --template react-ts
cd task-app
npm install zod
npm install --save-dev vitest @testing-library/react @testing-library/jest-dom jsdomVite react-ts template มี tsconfig strict แล้ว
src/types.ts
import { z } from "zod";
export const TaskSchema = z.object({
id: z.number(),
title: z.string(),
completed: z.boolean(),
});
export type Task = z.infer<typeof TaskSchema>;
export const TaskListSchema = z.array(TaskSchema);src/api.ts — typed fetch + validation
import { TaskSchema, TaskListSchema, type Task } from "./types.js";
const BASE = "https://jsonplaceholder.typicode.com";
async function request<T>(path: string, schema: { parse: (v: unknown) => T }, init?: RequestInit): Promise<T> {
const res = await fetch(BASE + path, {
...init,
headers: { "Content-Type": "application/json", ...init?.headers },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return schema.parse(await res.json());
}
export const taskApi = {
list: () => request("/todos?_limit=10", TaskListSchema),
toggle: (task: Task) =>
request(`/todos/${task.id}`, TaskSchema, {
method: "PATCH",
body: JSON.stringify({ completed: !task.completed }),
}),
};src/hooks/useAsync.ts — custom hook
import { useState, useEffect, useCallback } from "react";
type AsyncState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: string };
export function useAsync<T>(fn: () => Promise<T>, deps: unknown[] = []) {
const [state, setState] = useState<AsyncState<T>>({ status: "idle" });
const run = useCallback(async () => {
setState({ status: "loading" });
try {
const data = await fn();
setState({ status: "success", data });
} catch (error) {
setState({
status: "error",
error: error instanceof Error ? error.message : String(error),
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
useEffect(() => {
void run();
}, [run]);
return { state, refetch: run };
}src/store.ts — useReducer typed
import { type Task } from "./types.js";
export interface TaskState {
tasks: Task[];
filter: "all" | "active" | "completed";
}
export type TaskAction =
| { type: "set"; tasks: Task[] }
| { type: "toggle"; id: number }
| { type: "setFilter"; filter: TaskState["filter"] }
| { type: "clearCompleted" };
export function taskReducer(state: TaskState, action: TaskAction): TaskState {
switch (action.type) {
case "set":
return { ...state, tasks: action.tasks };
case "toggle":
return {
...state,
tasks: state.tasks.map((t) =>
t.id === action.id ? { ...t, completed: !t.completed } : t,
),
};
case "setFilter":
return { ...state, filter: action.filter };
case "clearCompleted":
return { ...state, tasks: state.tasks.filter((t) => !t.completed) };
default: {
const _exhaustive: never = action;
return state;
}
}
}
export function visibleTasks(state: TaskState): Task[] {
switch (state.filter) {
case "all": return state.tasks;
case "active": return state.tasks.filter((t) => !t.completed);
case "completed": return state.tasks.filter((t) => t.completed);
}
}src/components/TaskItem.tsx
import { type Task } from "../types.js";
interface TaskItemProps {
task: Task;
onToggle: (id: number) => void;
}
export function TaskItem({ task, onToggle }: TaskItemProps) {
return (
<li>
<label>
<input
type="checkbox"
checked={task.completed}
onChange={() => onToggle(task.id)}
/>
<span style={{ textDecoration: task.completed ? "line-through" : "none" }}>
{task.title}
</span>
</label>
</li>
);
}src/App.tsx
import { useReducer, useEffect } from "react";
import { useAsync } from "./hooks/useAsync.js";
import { taskApi } from "./api.js";
import { taskReducer, visibleTasks, type TaskState } from "./store.js";
import { TaskItem } from "./components/TaskItem.js";
const initialState: TaskState = { tasks: [], filter: "all" };
const FILTERS = ["all", "active", "completed"] as const;
export default function App() {
const [state, dispatch] = useReducer(taskReducer, initialState);
const { state: fetchState, refetch } = useAsync(() => taskApi.list(), []);
useEffect(() => {
if (fetchState.status === "success") {
dispatch({ type: "set", tasks: fetchState.data });
}
}, [fetchState]);
if (fetchState.status === "loading" || fetchState.status === "idle") {
return <p>กำลังโหลด...</p>;
}
if (fetchState.status === "error") {
return (
<div>
<p>ผิดพลาด: {fetchState.error}</p>
<button onClick={() => void refetch()}>ลองใหม่</button>
</div>
);
}
const tasks = visibleTasks(state);
return (
<main>
<h1>Tasks ({state.tasks.filter((t) => !t.completed).length} ค้าง)</h1>
<div>
{FILTERS.map((f) => (
<button
key={f}
disabled={state.filter === f}
onClick={() => dispatch({ type: "setFilter", filter: f })}
>
{f}
</button>
))}
<button onClick={() => dispatch({ type: "clearCompleted" })}>
ล้างที่เสร็จแล้ว
</button>
</div>
<ul>
{tasks.map((task) => (
<TaskItem
key={task.id}
task={task}
onToggle={(id) => dispatch({ type: "toggle", id })}
/>
))}
</ul>
</main>
);
}test — src/store.test.ts
import { describe, it, expect } from "vitest";
import { taskReducer, visibleTasks, type TaskState } from "./store.js";
const base: TaskState = {
tasks: [
{ id: 1, title: "a", completed: false },
{ id: 2, title: "b", completed: true },
],
filter: "all",
};
describe("taskReducer", () => {
it("toggle", () => {
const next = taskReducer(base, { type: "toggle", id: 1 });
expect(next.tasks[0]?.completed).toBe(true);
expect(next.tasks[1]?.completed).toBe(true); // ไม่แตะตัวอื่น
});
it("setFilter", () => {
const next = taskReducer(base, { type: "setFilter", filter: "active" });
expect(next.filter).toBe("active");
});
it("clearCompleted", () => {
const next = taskReducer(base, { type: "clearCompleted" });
expect(next.tasks).toHaveLength(1);
expect(next.tasks[0]?.id).toBe(1);
});
});
describe("visibleTasks", () => {
it("filter active", () => {
expect(visibleTasks({ ...base, filter: "active" })).toHaveLength(1);
});
});component test — src/App.test.tsx
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { TaskItem } from "./components/TaskItem.js";
describe("TaskItem", () => {
it("เรียก onToggle เมื่อคลิก checkbox", async () => {
const onToggle = vi.fn();
render(<TaskItem task={{ id: 1, title: "test", completed: false }} onToggle={onToggle} />);
screen.getByRole("checkbox").click();
expect(onToggle).toHaveBeenCalledWith(1);
});
});vitest.config.ts:
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: { environment: "jsdom", setupFiles: ["./src/test-setup.ts"] },
});จุดที่รวมทั้งซีรีส์
| ส่วน | บท |
|---|---|
component props typed (ไม่ใช้ React.FC) | 38 |
useReducer + discriminated union TaskAction + never exhaustive | 7, 23, 38 |
custom hook useAsync<T> + AsyncState<T> discriminated union | 12, 38 |
useEffect deps, useCallback | 38 |
| zod validate API response | 30 |
catch (error: unknown) → error message | 26 |
as const tuple (FILTERS) + typeof FILTERS[number] | 8 |
| Vitest + Testing Library | 34 |
เรื่องที่คนมักพลาด
useState<Task[]>()แทนuseReducerสำหรับ state ซับซ้อน — reducer + discriminated union ชัดกว่า- fetch แล้วไม่ validate — API เปลี่ยน = crash; zod
schema.parse useAsyncstate เป็น{ loading, data, error }(nullable ทั้งหมด) — discriminated union (status) narrow ได้void refetch()ลืม — floating promise;voidหรือ.catch- component test พึ่ง API จริง — mock
taskApiหรือทดสอบ reducer/component แยก (logic บริสุทธิ์) childrenเป็นJSX.Element— ใช้ReactNode(รับ string, array, null ด้วย)
สรุป
- props typed (
interface Props,function C(props: Props)— ไม่React.FC) - state ซับซ้อน =
useReducer+ discriminated unionAction—dispatchtype-safe,neverexhaustive - custom hook
useAsync<T>returnAsyncState<T>(discriminated unionstatus) — narrow ใน render - API layer —
fetch+ zodschema.parseที่ boundary as consttuple สำหรับ filter list +typeof FILTERS[number]= union- test: reducer/helper (logic บริสุทธิ์) + component (Testing Library) แยกจาก integration
จบซีรีส์ TypeScript — จาก let x: string ถึง generic constraint, mapped type, conditional type, และแอปที่ type ไหลจาก API ถึง UI ครบ คุณเข้าใจแล้วว่า type system ของ TypeScript ไม่ใช่แค่ “JavaScript ที่เข้มงวด” แต่เป็นเครื่องมือออกแบบที่ทำให้ทั้งทีมมั่นใจว่าโค้ดจะทำงานถูกก่อนกดรัน ก้าวต่อไปคือลองอ่าน type ของ library ที่คุณใช้ทุกวัน (React, zod) แล้วคุณจะเห็นเทคนิคทุกอย่างในบทเรียนนี้ทำงานจริง