TypeScript โปรเจกต์: to-do CLI
เป้าหมาย
todo add "ซื้อของ" --priority 2
todo list
todo list --all
todo done 1
todo remove 2setup
mkdir todo-cli && cd todo-cli
npm init -y
npm install commander zod
npm install --save-dev typescript tsx @types/node
npx tsc --init// package.json
{
"type": "module",
"bin": { "todo": "./dist/index.js" },
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"typecheck": "tsc --noEmit"
}
}// tsconfig.json (ส่วนสำคัญ)
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"outDir": "dist",
"rootDir": "src"
}
}src/task.ts
import { z } from "zod";
export const TaskSchema = z.object({
id: z.number().int().positive(),
title: z.string().min(1),
priority: z.number().int().min(1).max(5).default(1),
done: z.boolean().default(false),
createdAt: z.string().datetime(),
});
export type Task = z.infer<typeof TaskSchema>;
export const TaskListSchema = z.object({
tasks: z.array(TaskSchema),
nextId: z.number().int().positive(),
});
export type TaskList = z.infer<typeof TaskListSchema>;
export function emptyList(): TaskList {
return { tasks: [], nextId: 1 };
}
export function addTask(list: TaskList, title: string, priority: number): Task {
const task: Task = {
id: list.nextId,
title,
priority,
done: false,
createdAt: new Date().toISOString(),
};
list.tasks.push(task);
list.nextId += 1;
return task;
}
export function markDone(list: TaskList, id: number): Task {
const task = list.tasks.find((t) => t.id === id);
if (!task) throw new Error(`ไม่พบ task #${id}`);
task.done = true;
return task;
}
export function removeTask(list: TaskList, id: number): void {
const index = list.tasks.findIndex((t) => t.id === id);
if (index === -1) throw new Error(`ไม่พบ task #${id}`);
list.tasks.splice(index, 1);
}
export function pendingSorted(list: TaskList): Task[] {
return list.tasks
.filter((t) => !t.done)
.sort((a, b) => b.priority - a.priority || a.id - b.id);
}src/storage.ts
import { readFile, writeFile, rename } from "node:fs/promises";
import path from "node:path";
import os from "node:os";
import { TaskListSchema, type TaskList, emptyList } from "./task.js";
function dbPath(): string {
return process.env.TODO_FILE ?? path.join(os.homedir(), ".todo.json");
}
export async function loadList(): Promise<TaskList> {
let raw: string;
try {
raw = await readFile(dbPath(), "utf-8");
} catch (error) {
if (isNotFound(error)) return emptyList();
throw error;
}
const parsed: unknown = JSON.parse(raw);
const result = TaskListSchema.safeParse(parsed);
if (!result.success) {
throw new Error(`ไฟล์ ${dbPath()} เสียหาย: ${result.error.message}`);
}
return result.data;
}
export async function saveList(list: TaskList): Promise<void> {
const tmp = dbPath() + ".tmp";
await writeFile(tmp, JSON.stringify(list, null, 2));
await rename(tmp, dbPath()); // atomic
}
function isNotFound(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
error.code === "ENOENT"
);
}src/index.ts
#!/usr/bin/env node
import { Command } from "commander";
import { loadList, saveList } from "./storage.js";
import { addTask, markDone, removeTask, pendingSorted, type Task } from "./task.js";
const program = new Command();
program.name("todo").description("จัดการ to-do จากเทอร์มินัล").version("1.0.0");
program
.command("add <title>")
.description("เพิ่ม task")
.option("-p, --priority <number>", "ความสำคัญ 1-5", "1")
.action(async (title: string, options: { priority: string }) => {
const priority = Number(options.priority);
if (!Number.isInteger(priority) || priority < 1 || priority > 5) {
console.error("priority ต้องเป็น 1-5");
process.exit(2);
}
const list = await loadList();
const task = addTask(list, title, priority);
await saveList(list);
console.log(`เพิ่ม #${task.id}: ${task.title} (p${task.priority})`);
});
program
.command("list")
.description("แสดง task")
.option("-a, --all", "แสดง task ที่เสร็จแล้วด้วย")
.action(async (options: { all?: boolean }) => {
const list = await loadList();
const tasks = options.all ? list.tasks : pendingSorted(list);
if (tasks.length === 0) {
console.log("ไม่มี task");
return;
}
for (const task of tasks) {
console.log(formatTask(task));
}
});
program
.command("done <id>")
.description("ทำเครื่องหมายเสร็จ")
.action(async (id: string) => {
await runMutation((list) => markDone(list, parseId(id)));
console.log(`ทำเสร็จ #${id}`);
});
program
.command("remove <id>")
.alias("rm")
.description("ลบ task")
.action(async (id: string) => {
await runMutation((list) => removeTask(list, parseId(id)));
console.log(`ลบ #${id}`);
});
async function runMutation(fn: (list: Awaited<ReturnType<typeof loadList>>) => void) {
try {
const list = await loadList();
fn(list);
await saveList(list);
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
function parseId(input: string): number {
const n = Number(input);
if (!Number.isInteger(n) || n < 1) {
console.error(`id ไม่ถูกต้อง: ${input}`);
process.exit(2);
}
return n;
}
function formatTask(task: Task): string {
const mark = task.done ? "x" : " ";
return `[${mark}] #${String(task.id).padStart(3)} (p${task.priority}) ${task.title}`;
}
program.parseAsync().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
});รัน
npm run dev -- add "อ่านหนังสือ TypeScript" -p 3
npm run dev -- add "ล้างจาน" -p 1
npm run dev -- list[ ] # 1 (p3) อ่านหนังสือ TypeScript
[ ] # 2 (p1) ล้างจานnpm run dev -- done 1
npm run dev -- list --all[x] # 1 (p3) อ่านหนังสือ TypeScript
[ ] # 2 (p1) ล้างจานbuild + ใช้เป็น command:
npm run build
npm link
todo listจุดที่ใช้ความรู้จากบทก่อน
| ส่วน | บท |
|---|---|
z.infer<typeof Schema> = type | 30 |
zod safeParse validate ไฟล์ที่โหลด | 30 |
node:fs/promises, atomic write (tmp + rename) | 36 |
process.env.X ?? fallback | 36 |
catch (error: unknown) narrowing | 26, 27 |
discriminated union (safeParse result .success) | 7 |
Awaited<ReturnType<typeof fn>> | 16 |
exit code, process.exit | 36 |
ต่อยอด
--jsonoutput — สำหรับ script อื่น:console.log(JSON.stringify(tasks))- สี ด้วย
picocolors/chalk - due date field + เตือนที่เลยกำหนด
- เทสต์
task.ts(logic บริสุทธิ์) ด้วย Vitest (บทที่ 34) - config —
~/.todorc.json(default priority, sort order)
เรื่องที่คนมักพลาด
- ไม่ validate ไฟล์ที่โหลด — format เก่า / เสียหาย → crash แปลก ๆ; zod
safeParse - เขียนไฟล์ตรง ๆ (ไม่ atomic) — crash กลางคัน = ไฟล์เสีย; tmp + rename
Number(options.priority)ไม่เช็ค —add x --priority abc→ NaNcommanderaction callback ไม่ระบุ type ของ options — เป็นany; ประกาศ{ priority: string }program.parse()ไม่ใช่parseAsync()เมื่อ action เป็น async — error ไม่ถูกจับprocess.exitก่อนawait saveList— ไฟล์ไม่ถูกบันทึก
สรุป
commander—.command("add <title>").option("-p, --priority <n>").action(async (title, opts) => ...)- zod schema = source of truth:
TaskSchema→type Task = z.infer<...>+ validate ไฟล์ - โหลด → แก้ในหน่วยความจำ →
saveList(atomic: tmp + rename) หลังทุก mutation - แยก
task.ts(logic บริสุทธิ์ — ทดสอบได้) จากindex.ts(CLI) จากstorage.ts(I/O) parseAsync().catch(...),process.exit(1/2)ตาม error type
บทถัดไป โปรเจกต์ typed API client — wrapper รอบ fetch ด้วย generics + zod validation