TypeScript classes provide a clear and struc­tured way to organise data and behaviour 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 pro­gram­ming language based on JavaS­cript. Classes represent a struc­tured method for defining objects and for applying object-oriented pro­gram­ming (OOP). TypeScript classes are like blue­prints for creating objects that bundle logically related data and methods.

TypeScript contains all the functions of JavaS­cript 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 in­her­it­ance and ab­strac­tion, which fa­cil­it­ates the de­vel­op­ment of complex ap­plic­a­tions.

With TypeScript classes, you can create a clear hierarchy of classes that inherit prop­er­ties and methods. This promotes code reuse and struc­tur­ing. Class con­struct­ors enable instances to be ini­tial­ised and ensure con­sist­ent 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 JavaS­cript class syntax. A TypeScript class can contain various elements to define the structure and behaviour of objects. The main com­pon­ents are:

  • Prop­er­ties
  • Con­struct­ors
  • Methods

Prop­er­ties

Prop­er­ties 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
  • prop­er­ty­Name: the name of the property that you want to define
  • prop­er­ty­Type: 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.

Con­struct­or

The con­struct­or in TypeScript is a special method that is called when a class instance (object) is created. You need it to ini­tial­ise the prop­er­ties of an object. The con­struct­or es­sen­tially defines the initial state of an instance. You can specify para­met­ers in the con­struct­or to pass values when in­stan­ti­at­ing TypeScript classes.

The basic syntax of a con­struct­or in TypeScript is:

class ClassName {
    constructor(parameter1: Type1, parameter2: Type2, ...) {
    }
}
typescript
  • con­struct­or: each class can have a single con­struct­or. If no con­struct­or is defined, an empty con­struct­or is created by default.
  • parameter: Type: para­met­ers are optional, depending on the class and its re­quire­ments. Para­met­ers should be labelled with their data types.

An example of a con­struct­or:

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 con­struct­or that accepts two para­met­ers firstName and lastName. When creating an instance of this class, these para­met­ers are passed, and the con­struct­or ini­tial­ises the firstName and lastName prop­er­ties of the instance with the cor­res­pond­ing 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 op­er­a­tions in the context of a class.

class ClassName {
    // ...
    methodName(parameter1: Type1, parameter2: Type2, ...): ReturnType {
    }
    // ...
}
typescript
  • meth­od­Name: name of the method
  • parameter: Type: optional para­met­ers that the method accepts
  • Re­turn­Type: this is the data type that de­term­ines 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 para­met­ers.

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 prop­er­ties defined in the class and ini­tial­ised in the con­struct­or. The object person is created by the keyword new followed by the class name and the re­spect­ive para­met­ers. The method con­cat­en­ates 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 mech­an­isms to organise and control the structure and behaviour 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 prop­er­ties and methods inside and outside the class.

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

  • private: private refers to prop­er­ties and methods that can only be called within the class itself. They are in­ac­cess­ible to external code parts.

  • protected: prop­er­ties and methods marked with protected can be called by the class itself and by derived classes (in in­her­it­ance), 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.

In­her­it­ance

In­her­it­ance is a fun­da­ment­al concept in object-oriented pro­gram­ming (OOP) that is used in TypeScript and many other internet pro­gram­ming 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 prop­er­ties 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 prop­er­ties and methods from the parent class Animal. The class Dog overrides the makeSound method to add a specific behaviour while in­her­it­ing the name property from Animal.

Readonly

You can use readonly to declare prop­er­ties of TypeScript classes or objects as read-only. This means that once a read-only property has been ini­tial­ised, 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 ini­tial­ised in the con­struct­or. After ini­tial­isa­tion, pi can no longer be changed. If you try to modify the value of pi after ini­tial­isa­tion, TypeScript will generate a com­pil­a­tion error.

Cheap domain names – buy yours now
  • Free website pro­tec­tion with SSL Wildcard included
  • Free private re­gis­tra­tion for greater privacy
  • Free Domain Connect for easy DNS setup
7f1d9baf055ac1978a131b91080d5d00

117a1597efe473942f630cae75678a0b

6fe9ad4655c8a5b1928748d3fe74ed9a

d8f0a02ba8214fdd5d685d3903e5f4f9

bff069b69f77dc61e074e3909fcf800c

7a031ebda636ff7fd6d7bc2196481fc2

Go to Main Menu