Menu
Coddy logo textTech

Function to Add a Task

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 46 of 73.

challenge icon

Challenge

Easy

You are provided with the following from the previous challenge:

  • The Task interface with id (number), title (string), and status (literal type)
  • Three task variables: firstTask, secondTask, and thirdTask
  • The getTaskInfo function

Create a function named addTask that takes two parameters:

  • taskList of type Task[] (an array of Task objects)
  • title of type string (the title for the new task)

The function should:

  • Create a new task with a unique ID (use the length of the current array + 1)
  • Set the title to the provided title parameter
  • Set the status to 'todo'
  • Return a new array containing all existing tasks plus the new task

Create an initial task list by creating a variable named initialTasks of type Task[] containing firstTask and secondTask.

Use your addTask function to add a new task with the title "Review code changes" to initialTasks and store the result in a variable named updatedTasks.

Print the following outputs on separate lines:

  • Print the length of initialTasks
  • Print the length of updatedTasks
  • Call getTaskInfo with the last task in updatedTasks and print the result
  • Print the title of the newly added task (the last task in updatedTasks)
  • Print the status of the newly added task

Try it yourself

// TODO: Write your code here

// Create the Task interface
interface Task {
    id: number;
    title: string;
    status: 'todo' | 'in-progress' | 'done';
}

// Create the task variables
const firstTask: Task = {
    id: 1,
    title: "Learn TypeScript interfaces",
    status: 'todo'
};

const secondTask: Task = {
    id: 2,
    title: "Build task management app",
    status: 'in-progress'
};

const thirdTask: Task = {
    id: 3,
    title: "Write unit tests",
    status: 'done'
};

// Create the getTaskInfo function
function getTaskInfo(task: Task): string {
    return `Task ${task.id}: ${task.title} - ${task.status}`;
}

// Print the required outputs
console.log(getTaskInfo(firstTask));
console.log(getTaskInfo(secondTask));
console.log(getTaskInfo(thirdTask));
console.log(firstTask.status);
console.log(secondTask.title);

All lessons in Introduction To TypeScript