Skip to main content

Interfaces

Introduction to Interfaces in TypeScript

Interfaces are a fundamental aspect of TypeScript. They allow us to define the shape of an object, ensuring that the object has a specific set of properties, with the correct type. They are a powerful way to define contracts within your code and contracts with code outside of your project.

What are Interfaces?

In TypeScript, an interface is a way to define a contract on a function or an object. It provides a way to define the shape of an object, ensuring that the object has a specific set of properties, with the correct type.

Here is a simple example of an interface:

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

With this User interface, we can now create objects that satisfy this structure:

let user: User = { name: 'John Doe', age: 30 };

Optional Properties

Interfaces can also include optional properties. These properties are denoted with a ? at the end of the property name.

interface Product {
id: number;
name: string;
price?: number;
}

In this Product interface, price is an optional property. This means an object of type Product may or may not contain a price property.

Function Types

Interfaces are not limited to defining the structure of objects; they can also be used to define the types of functions.

interface SearchFunction {
(source: string, subString: string): boolean;
}

Here, we've defined a SearchFunction interface that describes a function that takes two arguments, both of type string, and returns a boolean.

Extending Interfaces

One interface can extend another, this allows you to copy the members of one interface into another with extends keyword, which gives more flexibility in how you separate your interfaces into reusable components.

interface Shape {
color: string;
}

interface Square extends Shape {
sideLength: number;
}

In the above example, Square interface has extended Shape interface. Now Square interface will have both color and sideLength properties.

Implementing Interfaces

Interfaces can be implemented in classes to ensure that the class adheres to a particular contract.

interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}

class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
}

In the above example, Clock class implements ClockInterface interface. So, Clock class now has to have currentTime property and setTime method.

Conclusion

Interfaces are a powerful tool in TypeScript to define the structure of objects and functions. They help to ensure type safety by enforcing that objects have certain properties, and that functions have certain parameters and return types. By understanding and using interfaces, you can write cleaner and safer code.