Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Interfaces

Learn how to define object structures, specify properties and methods, use optional and readonly properties, and implement interfaces in classes.

Simple Explanation: An interface defines the expected structure of an object. It specifies which properties and methods an object should provide, helping TypeScript check that the object follows the required contract.

1. What is an Interface?

An interface is a TypeScript feature used to describe the structure of an object. It can define properties, optional properties, readonly properties and method signatures.

We use the interface keyword to declare an interface. An object assigned to that interface must provide the required properties with compatible types.

Basic Syntax

interface Student {
    id: number;
    name: string;
    age: number;
}

const student1: Student = {
    id: 101,
    name: "Rahul",
    age: 22
};

console.log(student1.name);
console.log(student1.age);

Expected Output

Rahul
22

Here, Student defines three required properties. The student1 object supplies all three properties with the correct types.

2. Interface Workflow Diagram

This diagram explains how an interface defines a contract and how an object follows that contract.

📘
Declare Interface

Define required property and method types.

→
📦
Create Object

Provide the required properties and values.

→
🔍
Type Checking

TypeScript checks structural compatibility.

→
✅
Use Object

Access properties and call available methods.

Remember: Interfaces provide compile-time type checking. They do not automatically validate data received from an API or database at runtime.

3. Interface Properties

Properties define the data that an object is expected to contain. Each property can specify a name and a type.

Example: Employee Details

interface Employee {
    id: number;
    name: string;
    department: string;
    salary: number;
}

const employee1: Employee = {
    id: 1,
    name: "Priya",
    department: "IT",
    salary: 40000
};

console.log(employee1.name);
console.log(employee1.department);
console.log(employee1.salary);

Expected Output

Priya
IT
40000

Understanding the Properties

Property Type Purpose
id number Stores the employee ID.
name string Stores the employee name.
department string Stores the department name.
salary number Stores the salary value.

4. Optional Properties

Sometimes an object may contain a property, but that property is not required. TypeScript allows us to mark such properties with the question mark (?).

Example

interface Student {
    id: number;
    name: string;
    email?: string;
}

const student1: Student = {
    id: 101,
    name: "Rahul"
};

const student2: Student = {
    id: 102,
    name: "Priya",
    email: "priya@example.com"
};

console.log(student1.name);
console.log(student1.email ?? "Email not provided");

console.log(student2.name);
console.log(student2.email);

Expected Output

Rahul
Email not provided
Priya
priya@example.com

The email property is optional. Both objects are valid, even though only the second object provides an email address. The ?? operator supplies a fallback when the value is null or undefined.

5. Readonly Properties

The readonly modifier prevents a property from being reassigned after it has been initialized through normal TypeScript code. It is useful for values such as an employee ID that should not be changed after an object is created.

Example

interface Employee {
    readonly id: number;
    name: string;
}

const employee1: Employee = {
    id: 101,
    name: "Amit"
};

employee1.name = "Amit Sharma";

console.log(employee1.id);
console.log(employee1.name);

// This would cause a TypeScript error:
// employee1.id = 102;

Expected Output

101
Amit Sharma
Remember: A readonly property cannot normally be reassigned after initialization, but other mutable properties, such as name, can still change. The TypeScript readonly modifier is not a runtime security feature.

6. Methods in Interfaces

Interfaces can define method signatures. An implementing object or class must provide a compatible method implementation. The interface specifies the method's name, parameters and return type.

Example

interface Calculator {
    add(a: number, b: number): number;
    subtract(a: number, b: number): number;
}

const calculator: Calculator = {
    add(a, b) {
        return a + b;
    },

    subtract(a, b) {
        return a - b;
    }
};

console.log(calculator.add(20, 10));
console.log(calculator.subtract(20, 10));

Expected Output

30
10

Method Workflow Diagram

📘
Method Signature

The interface defines parameters and return type.

→
⚙️
Implementation

The object provides the method logic.

→
📥
Arguments

Call the method with compatible values.

→
✅
Return Result

The method returns a value matching its declared type.

7. Implementing an Interface in a Class

A TypeScript class can use the implements keyword to declare that it satisfies an interface contract. A concrete class must implement the required interface members.

Example

interface Person {
    name: string;
    age: number;

    displayInfo(): void;
}

class Student implements Person {
    constructor(
        public name: string,
        public age: number
    ) {}

    displayInfo(): void {
        console.log("Name: " + this.name);
        console.log("Age: " + this.age);
    }
}

const student1 = new Student("Neha", 23);

student1.displayInfo();

Expected Output

Name: Neha
Age: 23

Implementation Workflow

📋
Person Interface

Declares name, age and displayInfo().

→
🧱
Student Class

Uses implements Person and supplies the required members.

→
✅
Student Object

Uses the implemented properties and method.

Important: An interface describes the required structure; it does not provide the method implementation itself.

8. Extending Interfaces

An interface can extend another interface using the extends keyword. The child interface inherits the parent interface's requirements and can add more properties.

Example

interface Person {
    name: string;
    age: number;
}

interface Employee extends Person {
    employeeId: number;
    department: string;
}

const employee1: Employee = {
    name: "Priya",
    age: 25,
    employeeId: 1001,
    department: "IT"
};

console.log(employee1.name);
console.log(employee1.employeeId);
console.log(employee1.department);

Expected Output

Priya
1001
IT

Interface Inheritance Diagram

👤
Person

name: string

age: number

🔗
extends

Employee inherits Person's requirements.

💼
Employee

All Person properties

Plus employeeId and department

9. Advantages of Interfaces

Consistent Structure

Defines the expected shape of objects across an application.

Type Safety

Helps catch missing properties and incompatible types during development.

Reusability

Reuse interface definitions in functions, objects and classes.

Extensibility

Extend existing interfaces to define more specific structures.

Summary

Interfaces describe object structures through properties and method signatures. Optional properties use ?, readonly properties restrict reassignment, classes can implement interfaces using implements, and interfaces can extend other interfaces using extends.

Next, learn Type Aliases and how to create reusable names for object types, primitive types and other type expressions.