Create the task interface
- βοΈCreate a TypeScript interfaceLearn how to create a new Typescript interface to represent a task.
- βοΈUse the Typescript interfaceLearn how to use the Typescript interface to define the type of a variable.
- βοΈGenerate a unique identifierLearn how to generate a unique identifier with uuid package
Interface creation
You will create a new TypeScript interface to represent a task. Each task has 3 properties:
- id: a string representing the unique identifier of the task.
- title: a string representing the title of the task.
- description: a string representing the description of the task.
- createdAt: a date representing the creation date of the task.
π Instructions
-
Create a new folder called models in the
src/app
folder to store all the TypeScript interfaces of the application. -
Create a new file called
task.model.ts
in this new folder. -
Add the following code to the file:
Id Generation
We will generate a unique identifier for each task. This id will help you to find a given task uniquely. Such an id is usually generated by a backend server, but for this tutorial, you will generate it on the client side.
To do so, letβs use the uuid library. This library generates unique identifiers based on the current timestamp and a random number.
π Instructions
-
Install the
uuid
library by running the following command in the terminal:
Interface usage
Letβs create a local variable in the TaskListComponent class to store a list of tasks. You will use the Task interface to define the type of the tasks variable.
In JavaScript, you would define the tasks variable like this:
To assign a type to a variable in TypeScript, you can use the :
operator followed by the type of the variable:
π Instructions
-
Update the
src/app/task-list.component.ts
file.
βοΈ What you learned
You learned how to create your first TypeScript interface. Itβll help during this course to track errors and improve the code quality. You also learned how to use the TypeScript interface to define the variable type.
π¦ Quiz
What is the TypeScript keyword used to define the Task model in src/app/model/task.model.ts
file?
interface
type
class
What is the TypeScript keyword used to define the type of a variable?
title: string;
title = string
title ; string