TypeScript Interface: Understanding the Interfaces in TypeScript

TypeScript Interface

An Interface in TypeScript can be seen as a syntactical agreement that an entity is expected to abide by. To put it simply, an interface lays out the syntax that any entity is obligated to comply with.

Interfaces are like type aliases, but they’re only used for objects.

Interfaces establish properties, methods, and events, collectively known as the members of the interface. Interfaces only encompass the declaration of these members.

It’s the job of the class that uses the interface to define these members. This usually helps in making sure that the classes using the interface follow the same structure.

Syntax:

interface InterfaceName {
    propertyName: propertyType;
    methodName(): returnType;
}

Let’s take a look at the parts of the code:

  • InterfaceName is the name of the interface.
  • propertyName is the name of a property that the interface expects the implementing entity to have.
  • propertyType is the type of the property.
  • methodName is a method that the interface expects the implementing entity to define.
  • returnType is the type of value that the method returns.

For example:

interface Car {
    brand: string;
    model: string;
    year: number;
}

function showCarInfo(car: Car) {
    console.log(`This is a ${car.brand} ${car.model} from ${car.year}.`);
}

let myCar = { brand: "Toyota", model: "Corolla", year: 2024 };
showCarInfo(myCar);

As you can see in our given example, we have an interface called LabeledValue. It says that any object using it must have a piece of information (or property) called a label that is text or string.

The printLabel function takes one object as input. This object must have a label property that is text.

Also, rulebooks (interfaces) can be used for actions (functions).

Here’s an example:

interface Car {
    brand: string;
    model: string;
    year: number;
}

function showCarInfo(car: Car) {
    console.log(`This is a ${car.brand} ${car.model} from ${car.year}.`);
}

let myCar = { brand: "Toyota", model: "Corolla", year: 2024 };
showCarInfo(myCar);

In this example, the Car interface has three members: brand, model, and year. The showCarInfo function takes an object that follows the Car interface and prints out its information.

Interfaces can also be used for functions.

Here’s another example:

interface Greeting {
    (name: string): void;
}

const sayHello: Greeting = (website: string) => {
    console.log(`Hello, ${website}!`);
}

In this example, the Greeting interface represents a function that takes a string as an argument and does not return anything.

The sayHello function follows this interface and prints a greeting message.

Use Cases of TyspeScript Interfaces

How to Declare Interfaces?

Declaring interfaces in TypeScript is straightforward. You use the interface keyword followed by the name of the interface, then define the required properties and methods within curly braces.

Syntax:

interface interface_name {
}

For example:

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

As you can see, the User interface specifies that any object of this type must have a name property of type string and an age property of type number.

Here’s the complete code:

// Define the User interface
interface User {
  name: string;
  age: number;
}

// Create an object that follows the User interface
let user: User = {
  name: "Itsourcecode",
  age: 18
};

// Function to display user info
function displayUserInfo(user: User) {
  console.log(`User Name: ${user.name}`);
  console.log(`User Age: ${user.age}`);
}

// Use the function
displayUserInfo(user);

Output:

User Name: Itsourcecode
User Age: 18

How to use interface with Methods?

Interfaces can also include methods, providing a contract for functionality.

Here’s an example of an interface with a method:

interface Animal {
name: string;
speak(): void;
}


Any object implementing the Animal interface must have a name property and a speak method that returns void.

This is useful for defining behavior patterns across different objects or classes.

Here’s the complete code:

// Define the Animal interface
interface Animal {
  name: string;
  speak(): void;
}

// Create a class that implements the Animal interface
class Dog implements Animal {
  name: string;

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

  speak() {
    console.log(this.name + ' says arf!');
  }
}

// Create an object of the Dog class
let dog: Animal = new Dog('John');

// Call the speak method
dog.speak();

Output:

John says arf!

How to use Interfaces for Functions?

Did you know you can use interfaces to define function signatures?

It’s a great way to ensure consistency and improve readability.

Here’s an example:

interface AddFunction {
(a: number, b: number): number;
}

With this interface, any function that matches this signature—two number inputs and a number output—can be used wherever the AddFunction interface is expected.

Here’s the complete code:

// Define the AddFunction interface
interface AddFunction {
  (a: number, b: number): number;
}

// Create a function that matches the AddFunction interface
let add: AddFunction = function(x: number, y: number): number {
  return x + y;
}

// Use the function
let sum = add(20, 10);
console.log(`The sum is ${sum}.`);

Output:

The sum is 30.

How to use Extending Interfaces?

Interfaces in TypeScript are pretty versatile. You can extend them, merge them, and even use them with classes to ensure your code adheres to a specific contract. Let’s dive into some advanced interface concepts.

One powerful feature of TypeScript interfaces is that they can be extended.

This allows you to create new interfaces based on existing ones, adding or modifying properties as needed.

Here’s an example:

interface Vehicle {
make: string;
model: string;
}

interface Car extends Vehicle {
doors: number;
}

As you can see, the Car interface extends the Vehicle interface, inheriting its properties and adding a new one, doors.

Here’s the complete code:

// Define the Vehicle interface
interface Vehicle {
  make: string;
  model: string;
}

// Define the Car interface that extends Vehicle
interface Car extends Vehicle {
  doors: number;
}

// Create a car object that follows the Car interface
let myCar: Car = {
  make: "Toyota",
  model: "Corolla",
  doors: 4
};

// Function to display car info
function displayCarInfo(car: Car) {
  console.log(`Make: ${car.make}`);
  console.log(`Model: ${car.model}`);
  console.log(`Doors: ${car.doors}`);
}

// Use the function
displayCarInfo(myCar);

Output:

Make: Toyota
Model: Corolla
Doors: 4

Interfaces vs. Types

There’s often a question about whether to use interfaces or types in TypeScript. They both serve similar purposes but have subtle differences.

The main difference between interfaces and types is that interfaces are meant to define the shape of objects, while types are more flexible, allowing for unions, intersections, and other complex type definitions.

So, when should you use interfaces, and when should you use types? A good rule of thumb is to use interfaces for object-oriented design and classes and types for more complex data structures and unions.

Conclusion

Finally, we’re done discussing the interfaces in TypeScript, which can be seen as a syntactical agreement that an entity is expected to abide by. To put it simply, interfaces in TypeScript are like a guide for your code.

They help you shape your objects and keep your code consistent. They make your code neat, and easy to understand and help when working with others on big projects.

Whether you’re dealing with classes, objects, or functions, knowing how to use interfaces is important to get the most out of TypeScript.

I hope that this article helps you understand the TypeScript Interface.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment