TypeScript

13.Understanding Interfaces in TypeScript

Understanding Interfaces in TypeScript

TypeScript is a statically typed superset of JavaScript that adds several powerful features, one of which is Interfaces. Interfaces provide a way to define the shape of objects, ensuring that the objects adhere to a certain structure. They help in enforcing a contract between different parts of the application, allowing you to define properties, methods, and events that objects or classes must implement.

In this blog post, we will cover interfaces in TypeScript, how to declare them, use them with objects, and see their use with classes, inheritance, and arrays. We will also look at how interfaces provide a way to implement multiple inheritance in TypeScript, something that is otherwise not directly supported.


What is an Interface?

An interface in TypeScript is a proforma or a contract that defines the properties and methods an object or class should implement. Unlike classes, interfaces do not contain any implementation details. Instead, they provide a blueprint for objects or classes.

Key Points:

  • Interfaces only define the structure or type of an object.

  • Interfaces cannot contain any implementation code.

  • Interfaces can be implemented by classes to ensure that the class follows the structure defined in the interface.


Declaring an Interface

To declare an interface in TypeScript, we use the interface keyword followed by the interface name and the body (with the properties and methods that must be implemented).

Syntax:

interface InterfaceName {
property1: type;
property2: type;
method1(): returnType;
}

Example:

Here, we declare an interface Employee to represent the structure of an employee object:

interface Employee {
id: number;
firstName: string;
lastName: string;
house: boolean;
email: string;
}

Using Interfaces with Objects

Once we define an interface, we can create objects that implement the interface. The object must match the structure defined in the interface. If any properties are missing or have incorrect types, TypeScript will raise an error.

Example:

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  house: boolean;
  email: string;
}

const sales: Employee = {
  id: 1,
  firstName: 'Rajesh',
  lastName: 'Kumar',
  house: false,
  email: 'rajesh@gmail.com'
};

const customerSupport: Employee = {
  id: 2,
  firstName: 'Anju',
  lastName: 'Patel',
  house: true,
  email: 'anju@gmail.com'
};

 

In the above code:

  • The Employee interface defines the structure that objects must adhere to.

  • Both sales and customerSupport objects follow the structure defined in the Employee interface.


Optional Parameters in Interfaces

You can also define optional properties in an interface. To make a property optional, you append a question mark (?) to the property name.

Example:

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  house: boolean;
  email: string;
  car?:string
}

class EmployeeClass implements Employee {
  constructor(
    public id: number,
    public firstName: string,
    public lastName: string,
    public house: boolean,
    public email: string
  ) {}

  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }

  hasHousing(): string {
    return this.house ? 'Has housing' : 'No housing';
  }
}

// Create instances
const sales = new EmployeeClass(
  1,
  'Rajesh',
  'Kumar',
  false,
  'rajesh@gmail.com'
);

const customerSupport = new EmployeeClass(
  2,
  'Anju',
  'Patel',
  true,
  'anju@gmail.com'
);

console.log(sales.getFullName()); // "Rajesh Kumar"
console.log(customerSupport.hasHousing()); // "Has housing"

 

Explanation:

  • The car property is optional in the Employee interface. It can be provided or omitted when creating an object.

  • The sales object doesn’t define a car property, while the customerSupport object does.


Interfaces and Inheritance

Interfaces in TypeScript can be extended by other interfaces. This allows you to create a new interface that inherits properties and methods from one or more interfaces.

Example:

Simple Interface Inheritance

interface Student {
  roll: number;
}

interface WebDesignStudent extends Student {
  course: string;
}

const designer: WebDesignStudent = {
  roll: 2,
  course: 'Web Design'
};

console.log("Roll: " + designer.roll);
console.log("Course: " + designer.course);

 

Explanation:

  • The WebDesignStudent interface extends the Student interface, so it inherits the roll property.

  • It also adds a new property course.


Multiple Interface Inheritance

TypeScript supports multiple interface inheritance. You can extend more than one interface by separating the interfaces with commas. This allows you to combine properties from different interfaces into a single class or interface.

Example:

interface IParent1 {
  v1: number;
}

interface IParent2 {
  v2: number;
}

interface Child extends IParent1, IParent2 { }

const Iobj: Child = { v1: 12, v2: 23 };

console.log("value 1: " + Iobj.v1 + " value 2: " + Iobj.v2);

 

Explanation:

  • The Child interface extends both IParent1 and IParent2, inheriting properties v1 and v2.

  • The object Iobj must include both v1 and v2, as defined in the Child interface.


Interfaces and Arrays

Interfaces in TypeScript are capable of defining both the type of keys and values. This allows you to create complex types like arrays with specific types.

Example:

interface studentsList {
  [index: number]: string;
}

const nameList: studentsList = ["Rajesh", "Anju", "Kiran"];
console.log(nameList[0]); // Output: Rajesh

 

Explanation:

  • The studentsList interface uses an index signature to specify that the index (number) will map to a string value.

  • The nameList array is created using this interface, where the index is a number and the value is a string.


Using Interfaces with Classes

TypeScript allows classes to implement interfaces. When a class implements an interface, it is required to implement all the properties and methods defined by that interface.

Example:

interface Car {
  color: string;
}

class Mercedez implements Car {
  color: string;
  computerized: string;

  constructor(color: string, computerized: string) {
    this.color = color;
    this.computerized = computerized;
  }
}

const car = new Mercedez('Red', 'Yes');
console.log("Mercedez car is of color: " + car.color + " and its computerized: " + car.computerized);

 

Explanation:

  • The Car interface defines a color property.

  • The Mercedez class implements the Car interface and provides its own implementation for the color property and adds a new property computerized.


Interfaces and the instanceof Operator

You can use the instanceof operator to check if an object is an instance of a class that implements a certain interface. This is useful in certain situations, such as when working with multiple classes that implement the same interface.

Example:

interface Student { }

class StudentClass implements Student { }

const obj = new StudentClass();
const isStudent = obj instanceof StudentClass;

console.log(“Is the object an instance of StudentClass? “ + isStudent); // Output: true


Conclusion

Interfaces in TypeScript are a powerful way to define the structure of objects and classes. They allow you to create contracts that objects or classes must adhere to, ensuring that your code is consistent and follows the desired structure.

Key points covered in this blog post:

  • Declaring Interfaces: Use the interface keyword to define a contract for objects or classes.

  • Optional Parameters: Use ? to define optional properties in interfaces.

  • Inheritance: Interfaces can extend other interfaces, allowing you to reuse and combine multiple interfaces.

  • Interfaces with Arrays: Interfaces can define the type of values and keys in arrays.

  • Interfaces and Classes: Classes can implement interfaces to ensure they follow a specific structure.

Leave a Reply

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