<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: navid barsalari</title>
    <description>The latest articles on DEV Community by navid barsalari (@navid_barsalari_9e7ff05f3).</description>
    <link>https://dev.to/navid_barsalari_9e7ff05f3</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3153806%2F438cab5b-5988-4e98-971b-2d6b4291fdaa.png</url>
      <title>DEV Community: navid barsalari</title>
      <link>https://dev.to/navid_barsalari_9e7ff05f3</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/navid_barsalari_9e7ff05f3"/>
    <language>en</language>
    <item>
      <title>Slum Dunk in Typescript Interface</title>
      <dc:creator>navid barsalari</dc:creator>
      <pubDate>Mon, 12 May 2025 11:56:41 +0000</pubDate>
      <link>https://dev.to/navid_barsalari_9e7ff05f3/slum-dunk-in-typescript-interface-3f1i</link>
      <guid>https://dev.to/navid_barsalari_9e7ff05f3/slum-dunk-in-typescript-interface-3f1i</guid>
      <description>&lt;p&gt;&lt;strong&gt;Summary:&lt;/strong&gt; in this tutorial, you’ll learn about TypeScript interfaces and how to use them to enforce type-checking and we will explore interfaces in TypeScript.&lt;/p&gt;

&lt;p&gt;Interfaces in TypeScript are much more powerful and have some strange capabilities, such as extending from each other and from classes! Today, we will review all of them together.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7ucj6q9yerhig7kg5oe.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7ucj6q9yerhig7kg5oe.jpeg" alt="Image description" width="800" height="800"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;From Basics to Advanced Patterns and Best Practices Topics Covered:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Defining an Interface&lt;/li&gt;
&lt;li&gt;Optional Properties&lt;/li&gt;
&lt;li&gt;Implementing Interfaces in Classes&lt;/li&gt;
&lt;li&gt;Multiple Interface Implementation&lt;/li&gt;
&lt;li&gt;Implementing Interface for a Service Class&lt;/li&gt;
&lt;li&gt;Combining Interfaces (Interface Composition)&lt;/li&gt;
&lt;li&gt;Dynamic Implementation with Factory Pattern&lt;/li&gt;
&lt;li&gt;Merging Interfaces&lt;/li&gt;
&lt;li&gt;Generics in Interfaces&lt;/li&gt;
&lt;li&gt;Interview Questions&lt;/li&gt;
&lt;li&gt;Best Practices for TypeScript Interfaces&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Introduction to TypeScript interfaces&lt;/strong&gt;&lt;br&gt;
TypeScript interfaces define the contracts within your code. They also provide explicit names for type checking.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are TypeScript Interfaces?&lt;/strong&gt;&lt;br&gt;
At its core, an interface in TypeScript is a syntactical contract that defines the expected structure of an object. It provides a way to describe the shape of objects, including their properties and methods, without implementing any functionality. Interfaces solely focus on the structure and type-checking aspects, allowing for better code understanding and validation during development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax of TypeScript Interfaces&lt;/strong&gt;&lt;br&gt;
The syntax of a TypeScript interface is straightforward:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface InterfaceName {
    property1: type;
    property2: type;
    // Additional properties and methods can be defined here
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s a breakdown of the syntax elements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;interface: Keyword used to define an interface.&lt;/li&gt;
&lt;li&gt;InterfaceName: Name of the interface following TypeScript naming conventions.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;property1&lt;/em&gt;, &lt;em&gt;property2&lt;/em&gt;: Properties of the interface.&lt;/li&gt;
&lt;li&gt;type: TypeScript type annotation defining the type of each property(String, Number, Boolean, Object Type, Array, Tuple, Enum, Any , Unknown, Void, …)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s start with a simple example:&lt;br&gt;
&lt;strong&gt;Defining an Interface&lt;/strong&gt;&lt;br&gt;
In TypeScript, there are two ways to define an interface. The first method is to define it inline for an object. Another method is to create a separate interface and assign it to any object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getProductInfo(product: {name: string, price: number}): string {
 return `${product.name}: ${product.price} `;
}
const product = {
 name: "Laptop",
 price: 999.99
};
console.log(getProductInfo(product));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Laptop: 999.99

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following uses an interface Product that has two properties a string and another number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Product {
    name: string;
    price: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By convention, the interface names are in the PascalCase. They use a single capitalized letter to separate words in their names. For example, &lt;em&gt;Product&lt;/em&gt;, &lt;em&gt;Person&lt;/em&gt;, &lt;em&gt;UserProfile&lt;/em&gt;, and &lt;em&gt;FullName&lt;/em&gt;.&lt;br&gt;
After defining the &lt;em&gt;Person&lt;/em&gt;, interface, you can use it as a type. For example, you can annotate the function parameter with the interface name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getProductInfo(product: Product) {
    return `${product.name}: ${product.price} `;
}

const product = {
 name: "Laptop",
 price: 999.99
};

console.log(getProductInfo(product));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code now is easier to read than before.&lt;/p&gt;

&lt;p&gt;To make the code more concise, you can use the object destructuring feature of JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getProductInfo({ name, price }: Product) {
  return `${name}: ${price} `;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the argument, we destructure the properties of the &lt;em&gt;product&lt;/em&gt; object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ name, price }: Product

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;em&gt;getProductInfo()&lt;/em&gt; function will accept any object that has at least two string properties with the name &lt;em&gt;name&lt;/em&gt; and &lt;em&gt;price&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;For example, the following code declares an object that has six properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let product = {
  name: "Laptop",
  price: 999.99
  category: "Electronics",
  description: "High-performance laptop with 16GB RAM",
  weight: 2000,
  stock: 5
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since the &lt;em&gt;product&lt;/em&gt; object has two properties &lt;em&gt;name&lt;/em&gt; and &lt;em&gt;price&lt;/em&gt;, you can pass it on to the &lt;em&gt;getProductInfo()&lt;/em&gt; function as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let productInfo= getProductInfo(product);
console.log(productInfo); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Laptop: 999.99
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example in frontend:&lt;br&gt;
🔵 React Example (with TypeScript):&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Product.ts
export interface Product {
  id: string;
  name: string;
  price: number;
  description: string;
  images: string[];
  stock: number;
  category: string;
}

// ProductDisplay.tsx
const ProductDisplay: React.FC&amp;lt;{ product: Product }&amp;gt; = ({ product }) =&amp;gt; {
  return (
    &amp;lt;div className="product-card"&amp;gt;
      &amp;lt;img 
        src={product.images[0]} 
        alt={product.name}
        className="product-image"
      /&amp;gt;
      &amp;lt;h2 className="product-name"&amp;gt;{product.name}&amp;lt;/h2&amp;gt;
      &amp;lt;p className="product-description"&amp;gt;{product.description}&amp;lt;/p&amp;gt;
      &amp;lt;div className="product-details"&amp;gt;
        &amp;lt;span className="product-price"&amp;gt;${product.price.toFixed(2)}&amp;lt;/span&amp;gt;
        &amp;lt;span className="product-stock"&amp;gt;
          {product.stock &amp;gt; 0 ? 'In Stock' : 'Out of Stock'}
        &amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

// Usage in App.tsx
import React from 'react';
import { ProductDisplay } from './ProductDisplay';

const App = () =&amp;gt; {
  const product: Product = {
    id: "PROD001",
    name: "Premium Laptop",
    price: 999.99,
    description: "High-performance laptop with 16GB RAM and 512GB SSD",
    images: ["laptop1.jpg", "laptop2.jpg"],
    stock: 5,
    category: "Electronics"
  };

  return (
    &amp;lt;div className="app"&amp;gt;
      &amp;lt;h1&amp;gt;Product Details&amp;lt;/h1&amp;gt;
      &amp;lt;ProductDisplay product={product} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;🔴 Angular Example (with TypeScript):&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// product.ts
export interface Product {
  id: string;
  name: string;
  price: number;
  description: string;
  images: string[];
  stock: number;
  category: string;
}

// product-display.component.ts
import { Component, Input } from '@angular/core';
import { Product } from './product';

@Component({
  selector: 'app-product-display',
  template: `
    &amp;lt;div class="product-card"&amp;gt;
      &amp;lt;img [src]="product.images[0]" [alt]="product.name" class="product-image"&amp;gt;
      &amp;lt;h2 class="product-name"&amp;gt;{{ product.name }}&amp;lt;/h2&amp;gt;
      &amp;lt;p class="product-description"&amp;gt;{{ product.description }}&amp;lt;/p&amp;gt;
      &amp;lt;div class="product-details"&amp;gt;
        &amp;lt;span class="product-price"&amp;gt;${{ product.price | number:'1.2-2' }}&amp;lt;/span&amp;gt;
        &amp;lt;span class="product-stock"&amp;gt;
          {{ product.stock &amp;gt; 0 ? 'In Stock' : 'Out of Stock' }}
        &amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  `
})
export class ProductDisplayComponent {
  @Input() product!: Product;
}

// app.component.ts
import { Component } from '@angular/core';
import { Product } from './product';

@Component({
  selector: 'app-root',
  template: `
    &amp;lt;div class="app"&amp;gt;
      &amp;lt;h1&amp;gt;Product Details&amp;lt;/h1&amp;gt;
      &amp;lt;app-product-display [product]="currentProduct"&amp;gt;&amp;lt;/app-product-display&amp;gt;
    &amp;lt;/div&amp;gt;
  `
})
export class AppComponent {
  currentProduct: Product = {
    id: "PROD001",
    name: "Premium Laptop",
    price: 999.99,
    description: "High-performance laptop with 16GB RAM and 512GB SSD",
    images: ["laptop1.jpg", "laptop2.jpg"],
    stock: 5,
    category: "Electronics"
  };
}

// product.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductDisplayComponent } from './product-display.component';

@NgModule({
  declarations: [ProductDisplayComponent],
  imports: [CommonModule],
  exports: [ProductDisplayComponent]
})
export class ProductModule { }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;🟢 Vue 3 Example (with TypeScript + Composition API):&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Product.ts
export interface Product {
  id: string;
  name: string;
  price: number;
  description: string;
  images: string[];
  stock: number;
  category: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- ProductDisplay.vue --&amp;gt;
&amp;lt;template&amp;gt;
  &amp;lt;div class="product-card"&amp;gt;
    &amp;lt;img :src="product.images[0]" :alt="product.name" class="product-image"&amp;gt;
    &amp;lt;h2 class="product-name"&amp;gt;{{ product.name }}&amp;lt;/h2&amp;gt;
    &amp;lt;p class="product-description"&amp;gt;{{ product.description }}&amp;lt;/p&amp;gt;
    &amp;lt;div class="product-details"&amp;gt;
      &amp;lt;span class="product-price"&amp;gt;${{ product.price.toFixed(2) }}&amp;lt;/span&amp;gt;
      &amp;lt;span class="product-stock"&amp;gt;
        {{ product.stock &amp;gt; 0 ? 'In Stock' : 'Out of Stock' }}
      &amp;lt;/span&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script lang="ts" setup&amp;gt;
import { defineProps } from 'vue';
import type { Product } from './Product';

const props = defineProps&amp;lt;{ product: Product }&amp;gt;();
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- App.vue --&amp;gt;
&amp;lt;template&amp;gt;
  &amp;lt;div class="app"&amp;gt;
    &amp;lt;h1&amp;gt;Product Details&amp;lt;/h1&amp;gt;
    &amp;lt;ProductDisplay :product="currentProduct" /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script lang="ts" setup&amp;gt;
import ProductDisplay from './ProductDisplay.vue';
import type { Product } from './Product';

const currentProduct: Product = {
  id: "PROD001",
  name: "Premium Laptop",
  price: 999.99,
  description: "High-performance laptop with 16GB RAM and 512GB SSD",
  images: ["laptop1.jpg", "laptop2.jpg"],
  stock: 5,
  category: "Electronics"
};
&amp;lt;/script&amp;gt;

&amp;lt;!-- main.ts --&amp;gt;
import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;**Example in backend:&lt;br&gt;
📁 Backend Setup (Node.js + Express + TypeScript):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Person Interface (User.ts)**
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface User {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  age: number;
  isActive: boolean;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;** 2. Server (server.ts) **&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from 'express';
import { Person } from './Person';

const app = express();
const port = 3000;

app.use(express.json());

let people: Person[] = [
  { id: 1, firstName: 'John', lastName: 'Doe' },
  { id: 2, firstName: 'Jane', lastName: 'Smith' },
];

// GET all people
app.get('/people', (_req, res) =&amp;gt; {
  res.json(people);
});

// GET one person
app.get('/people/:id', (req, res) =&amp;gt; {
  const person = people.find(p =&amp;gt; p.id === parseInt(req.params.id));
  if (!person) return res.status(404).send('Not found');
  res.json(person);
});

// POST create person
app.post('/people', (req, res) =&amp;gt; {
  const { firstName, lastName } = req.body;
  const newPerson: Person = {
    id: people.length + 1,
    firstName,
    lastName
  };
  people.push(newPerson);
  res.status(201).json(newPerson);
});

// DELETE person
app.delete('/people/:id', (req, res) =&amp;gt; {
  people = people.filter(p =&amp;gt; p.id !== parseInt(req.params.id));
  res.status(204).send();
});

app.listen(port, () =&amp;gt; {
  console.log(`Server running at http://localhost:${port}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Optional Properties&lt;/strong&gt;&lt;br&gt;
We can make properties optional by adding a question mark (?) after the property name, Optional properties allow us to define interface properties that are not required to be implemented. This provides flexibility in implementing the interface.If we do not implement any of the properties, we will not receive any errors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface PersonInterface {
    name?: string;
    age?: number;
    address?: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Person implements PersonInterface {
    name: string;
    constructor(name: string, age?: number, address?: string) {
        this.name = name;
        if (age) {
            console.log(`Age: ${age}`);
        }
        if (address) {
            console.log(`Address: ${address}`);
        }
    }
}
const person1 = new Person("Alice");
const person2 = new Person("Bob", 30);
const person3 = new Person("Charlie", 25, "123 Main St");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Alice
Bob - Age: 30
Charlie - Age: 25, Address: 123 Main St
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;em&gt;age&lt;/em&gt; and &lt;em&gt;address&lt;/em&gt; are optional. The &lt;em&gt;Person&lt;/em&gt; class can choose to implement none, some, or all of these properties without causing any TypeScript errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional and Readonly Properties&lt;/strong&gt;&lt;br&gt;
Optional (?) and &lt;em&gt;readonly&lt;/em&gt; properties in interfaces provide flexibility and control by allowing properties to be optional or immutable after initialization. This enhances type safety and prevents unintended modification&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Product {
  id: number;
  name: string;
  description?: string;
  readonly price: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const product: Product = { id: 1, name: 'Laptop', price: 1500 };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;product.price = 1600; 
// Error: Cannot assign to 'price' because it is a read-only property
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Implementing Interfaces in Classes&lt;/strong&gt;&lt;br&gt;
Classes can also implement these interfaces, meaning they must define all the properties specified in the interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ProductInterface {
    name: string;
    price: number;
}
class Product implements ProductInterface {
    name: string;
    price: number;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, we can define methods in interfaces as well:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ProductInterface {
    name: string;
    price: number;
    currency: string;
    discountPercentage?: number;

    setName(name: string): void;
    setPrice(price: number, currency: string): void;
    applyDiscount(percentage: number): void;
    calculateFinalPrice(): number;
}

class Product implements ProductInterface {
    name: string;
    price: number;
    currency: string;
    discountPercentage: number = 0;

   constructor(name: string, price: number, currency: string) {
        this.name = name;
        this.price = price;
        this.currency = currency;
    }

    setName(name: string): void {
        this.name = name;
    }

    setPrice(price: number, currency: string): void {
        this.price = price;
        this.currency = currency;
    }

    applyDiscount(percentage: number): void {
        if (percentage &amp;gt;= 0 &amp;amp;&amp;amp; percentage &amp;lt;= 100) {
            this.discountPercentage = percentage;
        } else {
            throw new Error('Discount percentage must be between 0 and 100');
        }
    }

    calculateFinalPrice(): number {
        const discountAmount = (this.price * this.discountPercentage) / 100;
        return this.price - discountAmount;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;✅ 1. Multiple Interface Implementation:&lt;/strong&gt;&lt;br&gt;
A class can implement multiple interfaces to combine functionality:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Nameable {
    name: string;
    setName(name: string): void;
}

interface Pricable {
    price: number;
    setPrice(price: number): void;
}

class Product implements Nameable, Pricable {
    name: string;
    price: number;

    constructor(name: string, price: number) {
        this.name = name;
        this.price = price;
    }

    setName(name: string): void {
        this.name = name;
    }

    setPrice(price: number): void {
        this.price = price;
    }
}

const item = new Product("Laptop", 1000);
item.setName("Gaming Laptop");
item.setPrice(1200);

console.log(item);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Product { name: 'Gaming Laptop', price: 1200 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;✅ 2. Implementing Interface for a Service Class:&lt;/strong&gt;&lt;br&gt;
Interfaces are not just for data structures but also for defining the structure of service classes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ProductServiceInterface {
    getProducts(): Product[];
    addProduct(product: Product): void;
}

class Product {
    constructor(public name: string, public price: number) {}
}

class ProductService implements ProductServiceInterface {
    private products: Product[] = [];

    getProducts(): Product[] {
        return this.products;
    }

    addProduct(product: Product): void {
        this.products.push(product);
    }
}

const service = new ProductService();
service.addProduct(new Product("Book", 20));
console.log(service.getProducts());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Product { name: 'Book', price: 20 } ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;✅ 3. Combining Interfaces (Interface Composition):&lt;/strong&gt;&lt;br&gt;
We can combine multiple interfaces in a class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Identifiable {
    id: number;
}

interface Timestamped {
    createdAt: Date;
    updatedAt: Date;
}

class AuditableProductImpl implements Identifiable, Timestamped {
    id: number;
    createdAt: Date;
    updatedAt: Date;

    constructor(id: number) {
        this.id = id;
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    update(): void {
        this.updatedAt = new Date();
    }
}

class ProductImpl extends AuditableProductImpl {
    name: string;
    price: number;
    currency: string;
    discountPercentage: number = 0;

    constructor(
        id: number,
        name: string,
        price: number,
        currency: string
    ) {
        super(id);
        this.name = name;
        this.price = price;
        this.currency = currency;
    }

    setName(name: string): void { this.name = name; }
    setPrice(price: number, currency: string): void {
        this.price = price;
        this.currency = currency;
    }
    applyDiscount(percentage: number): void {
        this.discountPercentage = percentage;
    }
    calculateFinalPrice(): number {
        return this.price - (this.price * this.discountPercentage) / 100;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we demonstrate how to combine multiple interfaces (&lt;em&gt;Identifiable&lt;/em&gt; and &lt;em&gt;Timestamped&lt;/em&gt;) to form a more complex class structure. The &lt;em&gt;AuditableProductImpl&lt;/em&gt; class implements both interfaces, ensuring that each instance has &lt;em&gt;id&lt;/em&gt;, &lt;em&gt;createdAt&lt;/em&gt;, and &lt;em&gt;updatedAt&lt;/em&gt; properties. The &lt;em&gt;ProductImpl&lt;/em&gt; class extends &lt;em&gt;AuditableProductImpl&lt;/em&gt; to include additional product-specific properties (&lt;em&gt;name&lt;/em&gt;, &lt;em&gt;price&lt;/em&gt;, &lt;em&gt;currency&lt;/em&gt;, etc.) and methods (&lt;em&gt;setName&lt;/em&gt;, &lt;em&gt;setPrice&lt;/em&gt;, &lt;em&gt;applyDiscount&lt;/em&gt;, and &lt;em&gt;calculateFinalPrice&lt;/em&gt;). This approach promotes modular design and enforces consistent structure across related classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;✅ 4. Dynamic Implementation with Factory Pattern:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Notification {
    send(message: string): void;
}

class EmailNotification implements Notification {
    send(message: string): void {
        console.log(`Sending email with message: ${message}`);
    }
}

class SMSNotification implements Notification {
    send(message: string): void {
        console.log(`Sending SMS with message: ${message}`);
    }
}

class NotificationFactory {
    static createNotification(type: "email" | "sms"): Notification {
        if (type === "email") {
            return new EmailNotification();
        } else {
            return new SMSNotification();
        }
    }
}

const emailService = NotificationFactory.createNotification("email");
emailService.send("Hello via Email!");

const smsService = NotificationFactory.createNotification("sms");
smsService.send("Hello via SMS!");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we implement the Factory Pattern to dynamically create instances of different notification classes (&lt;em&gt;EmailNotification&lt;/em&gt; and &lt;em&gt;SMSNotification&lt;/em&gt;) that implement the Notification interface. The NotificationFactory class provides a single method, &lt;em&gt;createNotification&lt;/em&gt;, which accepts a type ("email" or "sms") and returns the appropriate notification instance. This approach decouples the client code from the specific implementations and allows for easy extension and maintenance of new notification types without modifying existing logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extending Interfaces&lt;/strong&gt;&lt;br&gt;
Extending interfaces in TypeScript allows one interface to inherit the properties and methods of another, enabling code reuse and building on existing type definitions. This promotes modularity and flexibility in type design.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Person {
  firstName: string;
  lastName: string;
}
interface Employee extends Person {
  employeeId: number;
  department: string;
}
const employee: Employee = {
  firstName: 'Charlie',
  lastName: 'Brown',
  employeeId: 123,
  department: 'Engineering'
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;em&gt;Employee&lt;/em&gt; interface extends the &lt;em&gt;Person&lt;/em&gt; interface, meaning it inherits the &lt;em&gt;firstName&lt;/em&gt; and &lt;em&gt;lastName&lt;/em&gt; properties from &lt;em&gt;Person&lt;/em&gt; while adding its own properties: &lt;em&gt;employeeId&lt;/em&gt; and &lt;em&gt;department&lt;/em&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;em&gt;Person&lt;/em&gt; interface defines basic personal information (&lt;em&gt;firstName&lt;/em&gt; and &lt;em&gt;lastName&lt;/em&gt;).&lt;/li&gt;
&lt;li&gt;The &lt;em&gt;Employee&lt;/em&gt; interface extends &lt;em&gt;Person&lt;/em&gt; and adds additional properties specific to employees (&lt;em&gt;employeeId&lt;/em&gt; and &lt;em&gt;department&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The employee object implements the Employee interface, which means it must include all properties from both Person and Employee, resulting in a complete object with firstName, lastName, employeeId, and department.&lt;/p&gt;

&lt;p&gt;This technique allows for reusability and extension of existing interfaces, promoting clean and scalable type design.&lt;/p&gt;

&lt;p&gt;another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface PersonInterface {
    name: string;
    age: number;
}

interface RegisterInterface extends PersonInterface {
    setName(name: string): void;
    getName(): string;
}

class Person implements RegisterInterface {
    name: string;
    age: number;

    public setName(name: string): void {
        this.name = name;
    }

    public getName(): string {
        return this.name;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>typescript</category>
      <category>interfacesegregation</category>
      <category>backend</category>
    </item>
  </channel>
</rss>
