تمرين إعادة البناء
Todo List JSON
أعد كتابة قائمة مهام TypeScript تخزن بياناتها كـ JSON.
typescript
~16 دقيقة
مبتدئ
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
declare const process: {
argv: string[];
};
type FileSystemModule = {
existsSync(path: string): boolean;
readFileSync(path: string, encoding: "utf8"): string;
writeFileSync(path: string, data: string): void;
};
declare function require(name: "fs"): FileSystemModule;
type TodoStatus = "open" | "done";
interface TodoItem {
id: number;
text: string;
status: TodoStatus;
}
const fs = require("fs");
const filePath = "todos.json";
function loadTodos(): TodoItem[] {
if (!fs.existsSync(filePath)) {
return [];
}
return JSON.parse(fs.readFileSync(filePath, "utf8")) as TodoItem[];
}
function saveTodos(todos: TodoItem[]): void {
fs.writeFileSync(filePath, JSON.stringify(todos, null, 2));
}
function addTodo(text: string): TodoItem {
const todos = loadTodos();
const nextId = todos.length === 0 ? 1 : Math.max(...todos.map((todo) => todo.id)) + 1;
const todo: TodoItem = { id: nextId, text, status: "open" };
saveTodos([...todos, todo]);
return todo;
}
const text = process.argv.slice(2).join(" ") || "Practice TypeScript";
const todo = addTodo(text);
console.log(`Added #${todo.id}: ${todo.text}`);اكتب هنا