
Classes
We should already be familiar with the basics of TypeScript classes, as we have declared some of them in previous chapters. We will now look at some details and OOP concepts through examples. Let's start by declaring a simple class:
class Person { public name: string; public surname: string; public email: string; public constructor( name: string, surname: string, email: string ) { this.email = email; this.name = name; this.surname = surname; } public greet() { console.log("Hi!"); } }
We use classes to represent the type of an object or entity. A class is composed of a name, properties (also known as attributes), and methods. Both methods and properties are known as members. Class properties are used to describe the object's characteristics, while class methods are used to describe its behavior.
The class in the preceding example is named Person and contains three attributes or properties (name, surname, and email) and two methods (constructor and greet).
A constructor is a special method used by the new keyword to create instances (also known as objects) of our class. We have declared a variable named me, which holds an instance of the Person class. The new keyword uses the Person class's constructor to return an object whose type is Person:
const person = new Person( "Remo", "Jansen", "remo.jansen@wolksoftware.com" );