API Data Type & Interface - Type vs Interface in TypeScript

In the last part, API was called using a service.

any type was used for API response.

In this part, proper data types are defined for API data.

For this, Interface is used.


What is Interface

Interface is used to define the data type of a large object.

When an object has many properties, interface makes code easy to manage.

Small values like name, number, string can be typed directly.

Large API response objects should use interface.


Why Interface is Needed

API product object contains many keys like id, title, description, category, price, images, etc.

Writing all data types directly in component is difficult.

Interface can be created once and reused in many files.

Interface can be imported wherever required.


Creating Interface File

A new file is created inside the service folder.

This file is used to define API response data type.

File name example:

product-api-response.ts


Interface for API Response

export interface ProductsApiResponse {
products: Product[];
}

products is an array.

Each item inside the array is an object.


Interface for Product Object

export interface Product {
id: number;
title: string;
description: string;
category: string;
price: number;
reviews: any[];
}

Only required keys are defined.

Extra keys are skipped to keep code simple.


Using Interface in Component

any is removed and interface is used.

this.productService.getProducts().subscribe(
(data: ProductsApiResponse) => {
this.productData.set(data.products);
}
);

Now TypeScript automatically knows the data type.

Earlier it was showing any.


Signal Data Type

Product list is an array.

So signal type is defined as array of Product.

productData = signal<Product[] | undefined>(undefined);

API returns multiple products, not a single object.


Type vs Interface

Interface is used for objects with many keys.

Type is used for variables, functions, union values.

Interface supports merging.

Type does not support merging.

Interface is better for API response objects.