TypeScript
Challenge 4: Mini app
Solve a task testing the full beginner level.
Challenge 4: Mini app
This challenge tests the entire beginner level. You will combine types, functions, union, and intersection to write a mini task app. First you will define the Task model and functions, then the PrioritizedTask type.
Exercise Task model and functions
Define a Task interface: id: string, title: string, done: boolean. Write a function addTask(tasks: Task[], title: string): void (id = String(tasks.length + 1), done = false). Write a function completeTask(tasks: Task[], id: string): void (find and set done = true). Add a task, complete it, and print the done value.
Show example solution
interface Task { id: string; title: string; done: boolean; }
function addTask(tasks: Task[], title: string): void {
tasks.push({ id: String(tasks.length + 1), title, done: false });
}
function completeTask(tasks: Task[], id: string): void {
const task = tasks.find(t => t.id === id);
if (task) {
task.done = true;
}
}
const tasks: Task[] = [];
addTask(tasks, "Süt al");
completeTask(tasks, "1");
console.log(tasks[0].done);
Exercise Combine PrioritizedTask
Define a Priority type as "low" | "high". Define a Task interface: id: string, title: string, done: boolean. Define the PrioritizedTask type as Task & { priority: Priority }. Create an object and print its priority field.
Show example solution
type Priority = "low" | "high";
interface Task { id: string; title: string; done: boolean; }
type PrioritizedTask = Task & { priority: Priority };
const pt: PrioritizedTask = {
id: "1",
title: "Süt al",
done: false,
priority: "high"
};
console.log(pt.priority);
Test yourself
-
What is done first in a mini app?
- First write the output
- Immediately call console.log
- Define types and interfaces
- First call the functions
Show answer
Define types and interfaces — A solid app defines types first; then functions operate on those types. Writing output is the last step.
-
Complete the done field type
interface Task { id: string; title: string; done: ____; }
Show answer
interface Task { id: string; title: string; done: boolean; }
-
Task model parts
- interface Task
- Task model
- id: string
- Identity field
- done: boolean
- Completion status
- title: string
- Title field
Next lesson: Beginner section exam