How to define and use TypeScript classes

TypeScript classes provide a clear and structured way to organize data and behavior in an object. This makes it easier for you to model entities and concepts in your code.

What are TypeScript classes?

Classes are a key concept of TypeScript, which is a programming language based on JavaScript. Classes represent a structured method for defining objects and for applying object-oriented programming (OOP). TypeScript classes are like blueprints for creating objects that bundle logically related data and methods.

TypeScript contains all the functions of JavaScript and also includes static typing. This allows you to specify data types for TypeScript functions, variables and classes so you can detect compile-time errors. In addition to type safety, TypeScript classes also support concepts such as inheritance and abstraction, which facilitates the development of complex applications.

With TypeScript classes, you can create a clear hierarchy of classes that inherit properties and methods. This promotes code reuse and structuring. Class constructors enable instances to be initialized and ensure consistent object creation.

What is the syntax for TypeScript classes?

The notation of TypeScript classes is similar to that of ECMAScript 6 (ES6) and is an extended version of the JavaScript class syntax. A TypeScript class can contain various elements to define the structure and behavior of objects. The main components are:

  • Properties
  • Constructors
  • Methods

Properties

Properties determine the state of an object. They store data values and can be annotated with data types so that they only have valid values.

class ClassName {
    propertyName: propertyType;
}
typescript
  • ClassName: The name of the class
  • propertyName: The name of the property that you want to define
  • propertyType: The data type of the property

Here is a concrete example:

class Person {
    name: string;
}
typescript

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

Constructor

The constructor in TypeScript is a special method that is called when a class instance (object) is created. You need it to initialize the properties of an object. The constructor essentially defines the initial state of an instance. You can specify parameters in the constructor to pass values when instantiating TypeScript classes.

The basic syntax of a constructor in TypeScript is:

class ClassName {
    constructor(parameter1: Type1, parameter2: Type2, ...) {
    }
}
typescript
  • constructor: Each class can have a single constructor. If no constructor is defined, an empty constructor is created by default.
  • parameter: Type: Parameters are optional, depending on the class and its requirements. Parameters should be labeled with their data types.

An example of a constructor:

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

In the example above, the Person class has a constructor that accepts two parameters firstName and lastName. When creating an instance of this class, these parameters are passed, and the constructor initializes the firstName and lastName properties of the instance with the corresponding values. this refers to the current instance of the class that the code is executed on.

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: Name of the method
  • parameter: Type: Optional parameters that the method accepts
  • ReturnType: This is the data type that determines the value that the method returns. If the method does not return anything, you can specify void.

To access a property or call a method on a class instance, use the dot operator . followed by the method name and the required 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 getFullName method is used to create and return the full name of the person. It accesses the values of the firstName and lastName properties 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 respective parameters. The method concatenates the two strings when called and returns the full name as a string. The output for the object person is therefore “John Doe”.

TypeScript class examples

TypeScript classes have various mechanisms to organize and control the structure and behavior of objects. Below, we present some concepts for using TypeScript classes.

Access

TypeScript offers three access modifiers: public, private and protected to control access to properties and methods inside and outside the class.

  • public (standard): Properties and methods marked with public can be called from anywhere, both inside and outside the class.

  • private: private refers to properties and methods that can only be called within the class itself. They are inaccessible to external code parts.

  • 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 can only be accessed within the Person class. However, you can call the greet method from outside the class.

Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that is used in TypeScript and many other internet programming languages. It enables a new class to be created on the basis of an existing base class or super class. The derived class (subclass) inherits the properties and methods of the base class and can extend or adapt them.

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

Using the keyword extends, the child class Dog inherits the properties and methods from the parent class Animal. The class Dog overrides the makeSound method to add a specific behavior while inheriting the name property from Animal.

Readonly

You can use readonly to declare properties of TypeScript classes or objects as read-only. This means that once a read-only property has been 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

The pi property is read-only in our example and is initialized in the constructor. After initialization, pi can no longer be changed. If you try to modify the value of pi after initialization, TypeScript will generate a compilation error.

$1 Domain Names – Register yours today!
  • Simple registration
  • Premium TLDs at great prices
  • 24/7 personal consultant included
  • Free privacy protection for eligible domains
Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top