Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What are Interfaces in TypeScript?

Welcome to the world of TypeScript, a programming language that extends JavaScript by adding optional static types. As someone who's learning programming, you might have come across this term 'Interfaces' and wondered what it is and how it works in TypeScript. In this blog post, we'll explore Interfaces in TypeScript, why they are useful, and how to use them effectively with actual code examples. We'll try to keep the jargon to a minimum, but if we do use any technical terms, we'll be sure to explain them as well. So, let's dive in!

What are Interfaces?

Think of an interface as a contract or an agreement between different parts of your code. In the context of TypeScript, an interface is a way to define the shape or structure of an object, which allows you to enforce certain rules about the properties and methods that objects should have. By using interfaces, you can ensure that your code behaves in a predictable manner and follows a specific pattern.

Let's use an analogy to better understand the concept of interfaces. Imagine you're building a house, and you have a blueprint that outlines the structure and design of the house. The blueprint ensures that the house is built according to specific rules, such as the number of rooms, the size of each room, and so on. In this case, the blueprint acts like an interface, which serves as a guide for the construction of the house.

Now that we have a basic understanding of what interfaces are, let's see how they work in TypeScript.

Interfaces in TypeScript

In TypeScript, interfaces are declared using the interface keyword, followed by the name of the interface and a set of curly braces {}. Inside the curly braces, you define the properties and methods that the interface should contain. Let's see an example:

interface Person {
    firstName: string;
    lastName: string;
    age: number;
}

In the example above, we've defined an interface called Person, which has three properties: firstName, lastName, and age. Each property has a specific type, such as string or number. This means that any object that implements the Person interface must have these three properties with the specified types.

Now, let's see how to use this interface in our code.

Implementing Interfaces

To use an interface, you can use the implements keyword followed by the interface name when defining a class. This tells TypeScript that the class must adhere to the structure defined by the interface. Let's create a class called Employee that implements the Person interface:

class Employee implements Person {
    firstName: string;
    lastName: string;
    age: number;

    constructor(firstName: string, lastName: string, age: number) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

In this example, we've created a class called Employee that implements the Person interface. This means that the Employee class must have the firstName, lastName, and age properties with the specified types. If we try to remove one of these properties or change their types, TypeScript will throw an error, ensuring that our code follows the structure defined by the interface.

Using Interfaces with Functions

Interfaces can also be used with functions to enforce specific input and output types. Let's create a function that takes a Person object as an argument and returns a greeting message:

function greet(person: Person): string {
    return `Hello, ${person.firstName} ${person.lastName}!`;
}

const employee = new Employee('John', 'Doe', 30);
console.log(greet(employee)); // Output: Hello, John Doe!

In this example, we've created a function called greet that takes a Person object as an argument and returns a string. By specifying the Person interface as the type for the person parameter, we're ensuring that the function can only be called with objects that implement the Person interface.

Optional Properties

Sometimes, you might want to allow an object to have properties that are not required by the interface. In this case, you can use the ? symbol to mark a property as optional:

interface Person {
    firstName: string;
    lastName: string;
    age: number;
    middleName?: string;
}

In this example, we've added an optional middleName property to the Person interface. This means that objects implementing the Person interface can have a middleName property, but it's not required.

Readonly Properties

Another useful feature of interfaces is the ability to mark properties as readonly. This means that the value of the property can only be assigned when the object is created and cannot be changed afterward. To mark a property as readonly, use the readonly keyword:

interface Person {
    readonly firstName: string;
    readonly lastName: string;
    age: number;
}

In this example, we've marked the firstName and lastName properties as readonly. This means that once a Person object is created, its firstName and lastName properties cannot be changed.

Conclusion

Interfaces in TypeScript are a powerful way to define the structure and behavior of your code. By using interfaces, you can ensure that your code follows specific patterns and behaves in a predictable manner. Whether you're working with classes, functions, or plain objects, interfaces can help you write more robust and maintainable code in TypeScript.

Remember the key points we covered in this blog post:

  • Interfaces are like contracts that define the structure and behavior of your code.
  • Use the interface keyword to declare an interface, and implements to use it in a class.
  • Interfaces can be used with functions to enforce specific input and output types.
  • Optional properties can be marked with the ? symbol, and readonly properties can be marked with the readonly keyword.

Now that you have a better understanding of interfaces in TypeScript, you can start using them in your projects to improve the quality and maintainability of your code. Happy coding!