TypeScript for Beginners: Building Your First To-Do List App
Learn how to create a simple to-do list app using TypeScript. This beginner-friendly tutorial walks you through the basics of setting up, typing, and manipulating tasks.
TypeScript is a powerful language that builds on JavaScript by adding types, making your code easier to understand and less error-prone. In this tutorial, we'll create a simple to-do list application to illustrate how TypeScript can improve your development experience. By the end, you'll have a clear idea of how to use interfaces, types, and functions in TypeScript.
Let's start by defining the structure of a task using a TypeScript interface. This helps us ensure each task has the right properties.
interface Task {
id: number;
title: string;
completed: boolean;
}Next, we'll create an array to store our tasks. Using the interface for type safety, we tell TypeScript that this array will only hold objects that conform to the Task interface.
let tasks: Task[] = [];Now, let's write a function to add a new task to our list. This function will take a task title as input, create a new Task object, and push it into our tasks array.
function addTask(title: string): void {
const newTask: Task = {
id: tasks.length + 1,
title,
completed: false
};
tasks.push(newTask);
console.log(`Added task: \"${title}\"`);
}To mark a task as complete, we need a function that updates the completed status. This function finds the task by its id and sets completed to true.
function completeTask(id: number): void {
const task = tasks.find(t => t.id === id);
if (task) {
task.completed = true;
console.log(`Completed task: \"${task.title}\"`);
} else {
console.log(`Task with id ${id} not found.`);
}
}Finally, let's create a function to display all tasks and their completion status in a friendly format.
function showTasks(): void {
console.log('To-Do List:');
tasks.forEach(task => {
const status = task.completed ? '[x]' : '[ ]';
console.log(`${status} ${task.id}: ${task.title}`);
});
}Let's see how this works in practice by adding some tasks, completing one, and displaying the list:
addTask('Learn TypeScript basics');
addTask('Build a to-do list app');
addTask('Test the app');
completeTask(2);
showTasks();When you run this code, you should see output indicating the tasks you added, marking one as complete, and a final list showing the status of all tasks. This simple project demonstrates how TypeScript's typing and structure help you manage your data with clarity and confidence.
You can expand this app by adding features like deleting tasks, editing titles, or saving the list to local storage. As you continue learning TypeScript, try experimenting with more advanced types and interfaces to strengthen your skills.