0
0
Angularframework~5 mins

Interfaces for data models in Angular

Choose your learning style9 modes available
Introduction

Interfaces help define the shape of data clearly. They make your code easier to understand and safer by checking data types.

When you want to describe what properties an object should have.
When you receive data from a server and want to ensure it matches expected fields.
When you want to share a data structure across multiple components or services.
When you want to catch mistakes early by checking data types during development.
Syntax
Angular
export interface ModelName {
  property1: type1;
  property2: type2;
  optionalProperty?: type3;
}

Use export to share the interface across files.

Optional properties use a question mark ?.

Examples
This interface describes a user with an optional email.
Angular
export interface User {
  id: number;
  name: string;
  email?: string;
}
Defines a product with id, title, and price.
Angular
export interface Product {
  id: number;
  title: string;
  price: number;
}
Describes a todo item with a completion status.
Angular
export interface Todo {
  id: number;
  task: string;
  completed: boolean;
}
Sample Program

This Angular component uses an interface Book to define the shape of book objects. It shows a list of books with optional published year.

Angular
import { Component } from '@angular/core';

export interface Book {
  id: number;
  title: string;
  author: string;
  publishedYear?: number;
}

@Component({
  selector: 'app-book-list',
  template: `
    <h2>Book List</h2>
    <ul>
      <li *ngFor="let book of books">
        <strong>{{ book.title }}</strong> by {{ book.author }}
        <span *ngIf="book.publishedYear">({{ book.publishedYear }})</span>
      </li>
    </ul>
  `
})
export class BookListComponent {
  books: Book[] = [
    { id: 1, title: 'Angular Basics', author: 'Jane Doe', publishedYear: 2022 },
    { id: 2, title: 'Learning TypeScript', author: 'John Smith' }
  ];
}
OutputSuccess
Important Notes

Interfaces do not exist in the final JavaScript code; they are only for development time checks.

Use interfaces to improve code readability and avoid bugs from wrong data shapes.

Summary

Interfaces define the expected structure of data objects.

They help catch errors early by checking types during development.

Use them to keep your Angular app organized and clear.