Interfaces in TypeScript



Interfaces in TypeScript

An interface in TypeScript is a blueprint that defines the structure of an object. It specifies what properties and methods an object should have, without providing the implementation.

Why use Interfaces?

  • Improves code readability
  • Provides type safety
  • Supports code reusability
  • Makes applications easier to maintain
  • Enables better IntelliSense in IDEs
  1. Basic Interface

interface Student {

id: number;

name: string;

course: string;

}

const student: Student = {

id: 101,

name: “Anand”,

course: “Playwright”

};

console.log(student.name);

Output

Anand

  1. Optional Properties

Use ? for optional properties.

interface Employee {

id: number;

name: string;

email?: string;

}

const emp1: Employee = {

id: 1,

name: “John”

};

const emp2: Employee = {

id: 2,

name: “David”,

email: “david@gmail.com”

};

  1. Readonly Properties

Cannot be modified after object creation.

interface User {

readonly id: number;

name: string;

}

const user: User = {

id: 100,

name: “Anand”

};

user.name = “Rahul”;   // Allowed

// user.id = 200;      // Error

  1. Interface with Methods

interface Calculator {

add(a: number, b: number): number;

}

class MathOperation implements Calculator {

add(a: number, b: number): number {

return a + b;

}

}

const obj = new MathOperation();

console.log(obj.add(10,20));

Output

30

  1. Interface for Function Types

interface Multiply {

(x: number, y: number): number;

}

const multiply: Multiply = (a, b) => a * b;

console.log(multiply(5,4));

Output

20

  1. Interface with Arrays

interface Student {

id: number;

name: string;

}

const students: Student[] = [

{ id: 1, name: “Anand” },

{ id: 2, name: “Rahul” },

{ id: 3, name: “John” }

];

students.forEach(student =>

console.log(student.name)

);

  1. Interface Extension (Inheritance)

One interface can inherit another.

interface Person {

name: string;

}

interface Employee extends Person {

employeeId: number;

}

const emp: Employee = {

name: “Anand”,

employeeId: 1001

};

console.log(emp);

  1. Multiple Interface Inheritance

interface Address {

city: string;

}

interface Contact {

phone: string;

}

interface Employee extends Address, Contact {

name: string;

}

const emp: Employee = {

name: “Anand”,

city: “Hyderabad”,

phone: “9876543210”

};

console.log(emp);

  1. Interface Implemented by Class

interface Animal {

makeSound(): void;

}

class Dog implements Animal {

makeSound(): void {

console.log(“Bark…”);

}

}

const dog = new Dog();

dog.makeSound();

  1. Interface with Constructor

interface Person {

name: string;

}

interface PersonConstructor {

new (name: string): Person;

}

class Student implements Person {

constructor(public name: string) {}

}

const student = new Student(“Anand”);

console.log(student.name);

  1. Index Signature

Allows dynamic property names.

interface Marks {

[subject: string]: number;

}

const marks: Marks = {

Maths: 95,

English: 90,

Science: 98

};

console.log(marks.Maths);

  1. Interface with Nested Objects

interface Address {

city: string;

state: string;

}

interface Employee {

id: number;

name: string;

address: Address;

}

const emp: Employee = {

id: 1,

name: “Anand”,

address: {

city: “Hyderabad”,

state: “Telangana”

}

};

console.log(emp.address.city);

  1. Interface vs Type Alias
Interface Type Alias
Used to define object structure Can represent objects, primitives, unions, tuples, etc.
Supports extends Uses & for composition
Can be merged (declaration merging) Cannot be merged
Commonly used for OOP design Better for complex types

Interface

interface Student {

id: number;

name: string;

}

Type

type Student = {

id: number;

name: string;

};

  1. Declaration Merging (Unique Feature)

Interfaces with the same name are automatically merged.

interface Student {

id: number;

}

interface Student {

name: string;

}

const student: Student = {

id: 1,

name: “Anand”

};

This works because TypeScript merges both interface declarations.

Real-Time Example (Playwright)

Interfaces are commonly used to represent test data.

interface LoginUser {

username: string;

password: string;

}

const admin: LoginUser = {

username: “admin@test.com”,

password: “Admin@123”

};

test(“Login Test”, async ({ page }) => {

await page.goto(“https://example.com”);

await page.fill(“#username”, admin.username);

await page.fill(“#password”, admin.password);

await page.click(“button[type=’submit’]”);

});

Another example for API response:

interface UserResponse {

id: number;

name: string;

email: string;

}

const response = await page.request.get(“/users/1”);

const user: UserResponse = await response.json();

console.log(user.name);

import {Page,chromium,test} from “@playwright/test”;

interface infStudent

{

studentId:number;

studentName:string;

getStudentDetails():string;

}

class Student implements infStudent

{

studentId:number;

studentName:string;

constructor(studentId:number,studentName:string)

{

this.studentId=studentId;

this.studentName=studentName;

}

getStudentDetails():string {

return `Student ID: ${this.studentId}, Name: ${this.studentName}`;

}

}

test(‘Using interface’, async () => {

let student1: infStudent = new Student(1, “Anand”);

console.log(student1.studentId);

console.log(student1.studentName);

console.log(student1.getStudentDetails());

});

Tags: ,
Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!