Search⌘ K
AI Features

Classes and Interfaces

Explore how classes and interfaces work together in TypeScript to define object properties and behaviors. Understand the role of interfaces as contracts for classes and how duck typing allows type compatibility without explicit implementation. This lesson helps you write flexible and error-resistant code using object-oriented principles.

Relationship between classes and interfaces

There is a very strong relationship between classes and interfaces, particularly in object-oriented design patterns. An interface describes a custom type and can include both properties and functions. A class is the definition of an object, also including its properties and functions. This allows us to use interfaces to describe some common behavior within a set of classes and write code that will work with this set of classes.

As an example of this, consider the following class definitions:

TypeScript 4.9.5
// Define a class ClassA with a method print
class ClassA {
// Method print with a void return type
print(): void {
// Log message indicating that ClassA.print has been called
console.log(`ClassA.print() called.`)
};
}
// Define a class ClassB with a method print
class ClassB {
// Method print with a void return type
print(): void {
// Log message indicating that ClassB.print has been called
console.log(`ClassB.print() called.`)
};
}
Class definitions

Here, we have class definitions for two classes, named ClassA (lines 2–8) and ClassB (lines 11–17). Both of these ...