Define a Task Interface
Learn how to define a Task interface in Angular.
Creating Interfaces
Section titled “Creating Interfaces”You will create a new TypeScript interface to represent a task. Each task has 4 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
We use interfaces to represent our entities and also the business models of
the project. These business models and entities are therefore quite different
from the component model as our app.ts.
Instructions
Section titled “Instructions”-
Create a new folder called models in the
src/appfolder to store all TypeScript interfaces for the application.src└─ app└─ models -
Create a new file called
task.model.tsin this new folder.src└─ app└─ models└─ task.model.ts -
Add the following code to the file:
task.model.ts export interface Task {id: string;title: string;description: string;createdAt: Date;}
Generating Identifiers
Section titled “Generating Identifiers”You will generate a unique identifier for each task. This identifier will help you uniquely find a given task. Such an identifier is typically generated by a backend server, but for this tutorial, you will generate it on the client side.
For this, you will use the uuid library. This library generates unique identifiers based on the current timestamp and a random number.
-
Install the uuid library by running the following command in the terminal:
Terminal window npm install uuid && npm i --save-dev @types/uuid
Using the Interface
Section titled “Using the Interface”A local variable will be created in the TaskList component 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:
tasks = [ { title: "Task 1", description: "Description of task 1", createdAt: new Date(), }, { title: "Task 2", description: "Description of task 2", createdAt: new Date(), },];To assign a type to a variable in TypeScript, you can use the : operator followed by the variable type:
tasks: Task[] = [ { title: "Task 1", description: "Description of task 1", createdAt: new Date(), }, { title: "Task 2", description: "Description of task 2", createdAt: new Date(), },];The variable won’t be added it to your code, as we’ll firstly introduce a new concept in the next step.
You have learned how to create your first TypeScript interface. This will help during this course to track errors and improve code quality. You have also learned how to use the TypeScript interface to define a variable type.