⊗tsSpIfCII 27 of 37 menu

Interfaces for OOP classes in TypeScript

Interfaces in TypeScript are also widely used as templates for classes. To apply the desired interface to a class, the keyword implements is written after the class name and then the interface name.

Interfaces describe only public properties and methods of a class. The private part is defined in the class itself and is not described in the interface.

Let's try it in practice. Let's say we have the following interface that defines a property and a method:

interface IUser { name: string; greet(): string; }

Let's make a class that implements this interface. In this class, we should implement the property name and the method greet:

class User implements IUser { name: string; constructor(name: string) { this.name = name; } greet() { return `hello, ${this.name}!`; } }

Create an interface IMath with properties num1 and num2 and a method getDiv that will divide the first number by the second.

Make a class Math that implements the interface IMath.

swcssvplen