AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

TypeScript Classes: Tutorial and Practical Examples

PARTAGEZ

TypeScript classes provide an organized and transparent way to structure data and actions within an object. This makes modeling entities and concepts in your code easier and more intuitive.

What are TypeScript classes used for?

Classes are a key concept in the TypeScript programming language, which is based on JavaScript. They represent a structured method for creating objects according to the principle of object-oriented programming (OOP, Object-Oriented Programming). These classes act as schemas, allowing you to generate objects that integrate both data and tightly connected functions.

TypeScript contains all the functions of JavaScript and additionally includes the static typing. This makes it possible to specify data types for TypeScript functions, variables, and classes to detect errors at compile time. In addition to type safety, TypeScript classes support concepts such as inheritance and abstraction, making it easier to develop complex applications.

Using TypeScript classes, it is possible to establish a ordered class hierarchy allowing inheritance of properties and methods, which encourages code reuse and efficient structuring. Constructors within these classes play a crucial role in initializing instances, ensuring consistent and compliant object creation.

Writing TypeScript classes is similar to writing ECMAScript 6 (ES6) and is a more elaborate version of JavaScript class syntax. A class in TypeScript can contain different elements to define the structure and behavior of objects. The main elements are:

  • Properties
  • Builder
  • Methods

Properties

Properties determine thestate of an object. They store data values ​​and can be annotated with data types so that they only contain valid values.

class ClassName {
    propertyName: propertyType;
}

typescript

  • ClassName : the name of the class
  • propertyName : the name of the property you want to set
  • propertyType : the data type of the property

Here is a concrete example:

class Person {
    name: string;
}

typescript

First, a class Person is defined with a property name Of type string. This means that instances of the class Person have a property name Who stores strings (strings).

Builder

In TypeScript, the constructor is a single method that is activated when generating an instance (an object) of a class. Its role is crucial to define the initial properties of an object. Furthermore, this constructor establishes the initial state of the instance. It is possible to insert parameters in it to provide specific values ​​when creating instances of TypeScript classes.

The basic syntax of a constructor in TypeScript is:

class ClassName {
    constructor(parameter1: Type1, parameter2: Type2, ...) {
    }
}

typescript

  • constructor : each class can have only one constructor. If no constructor is defined, an empty constructor is created by default.
  • parameter: type : Parameters are optional and depend on the class and its requirements. Parameters must be identified by their data type.

Here is an example of a constructor:

class Person {
    firstName: string;
    lastName: string;
    constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

typescript

In this example, the class Person includes a constructor that requires two parameters, firstName And lastName. When creating an instance of the class, these parameters must be provided, allowing the constructor to assign the received values ​​to the properties. firstName And lastName of the instance. The term this is used to refer to the current instance of the class, on which the code is running.

Methods

In TypeScript, methods are functions that can be defined in classes and applied to their instances. Methods allow you to perform certain actions or operations in the context of a class.

class ClassName {
    // ...
    methodName(parameter1: Type1, parameter2: Type2, ...): ReturnType {
    }
    // ...
}

typescript

  • methodName : method name
  • parameter: type : optional parameters accepted by the method
  • ReturnType : data type that determines the value the method returns. If the method does not return anything, you can specify void.

To access a property or call a method on an instance of a class, use the dot operator . followed by the method name and any necessary arguments if the method expects parameters.

class Person {
    firstName: string;
    lastName: string;
    constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    getFullName(): string {
        return this.firstName + " " + this.lastName;
    }
}
const person = new Person("John", "Doe");
const fullName = person.getFullName();

typescript

The method getFullName is used to create and return the full name of the person. It accesses the values ​​of the properties firstName And lastNamewhich were defined in the class and initialized in the constructor. The object person is created by the keyword new followed by the class name and the corresponding parameters. When called, the method will concatenate the two strings and will return the full name as a string. The result for the object person so is “John Doe”.

TypeScript Classes: Usage Examples

TypeScript classes have different mechanisms for organizing and controlling the structure and behavior of objects. Below we present different uses.

Visibility

Visibility in TypeScript classes governs access to properties and methods inside and outside the class. TypeScript provides three visibility modifiers: public, private And protected.

  • public (standard) : properties and methods marked with public can be called from anywhere, both inside and outside the classroom.
  • private : private refers to properties and methods that can only be called from within the class itself. They are inaccessible to external parts of code.
  • protected : properties and methods marked with protected can be called by the class itself and by derived classes (in inheritance), but not by external code.
class Person {
    private socialSecurityNumber: string;
    constructor(ssn: string) {
        this.socialSecurityNumber = ssn;
    }
    greet() {
        console.log("Hello, I am a person with SSN: " + this.socialSecurityNumber);
    }
}
const person = new Person("123-45-6789");
person.greet();

typescript

In this example, socialSecurityNumber is a private property that is only accessible inside the class Person. The method greet can however be called from outside.

Legacy

Inheritance is a fundamental concept in object-oriented programming, used in TypeScript and many other web programming languages. It allows you to create a new class from an existing base class or superclass existing. The derived class (subclass) then inherits the properties and methods of the base class and can extend or adapt it.

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    makeSound() {
        console.log("Some generic sound");
    }
}
class Dog extends Animal {
    makeSound() {
        console.log(this.name + " barks");
    }
}
const myDog = new Dog("Buddy");
myDog.makeSound();

typescript

Here, the class Dog inherits from base class Animal using the keyword extends. The derived class Dog overwrite method makeSound to add specific behavior, while taking ownership name of Animal.

Readonly

The keyword readonly can be used to declare properties of TypeScript classes or objects like read only (Read only). This means that after a read-only property is initialized, its value can no longer be changed.

class Circle {
    readonly pi: number = 3.14159;
    radius: number;
    constructor(radius: number) {
        this.radius = radius;
    }
    getArea() {
        return this.pi    *this.radius*    this.radius;
    }
}
const myCircle = new Circle(5);
console.log(myCircle.getArea()); // Output: ≈ 78,54

typescript

In this example, the property pi is defined as read-only and is assigned a value when initialized in the constructor. Once initialized, changing pi is forbidden. Any attempt to change its value after it has been initialized will result in a compilation error by TypeScript.

Cheap Internet Domain

Much more than just a domain!

Personalize your online presence with a relevant domain name.

E-mail

SSL Certificate

24/7 Support

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact