Type­Script classes provide a clear and struc­tured 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 Type­Script classes?

Classes are a key concept of Type­Script, which is a pro­gram­ming language based on JavaScript. Classes represent a struc­tured method for defining objects and for applying object-oriented pro­gram­ming (OOP). Type­Script classes are like blue­prints for creating objects that bundle logically related data and methods.

Type­Script contains all the functions of JavaScript and also includes static typing. This allows you to specify data types for Type­Script functions, variables and classes so you can detect compile-time errors. In addition to type safety, Type­Script classes also support concepts such as in­her­i­tance and ab­strac­tion, which fa­cil­i­tates the de­vel­op­ment of complex ap­pli­ca­tions.

With Type­Script 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­struc­tors enable instances to be ini­tial­ized and ensure con­sis­tent object creation.

What is the syntax for Type­Script classes?

The notation of Type­Script classes is similar to that of EC­MAScript 6 (ES6) and is an extended version of the JavaScript class syntax. A Type­Script class can contain various elements to define the structure and behavior of objects. The main com­po­nents are:

  • Prop­er­ties
  • Con­struc­tors
  • 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;
}
type­script
  • 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;
}
type­script

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­struc­tor

The con­struc­tor in Type­Script is a special method that is called when a class instance (object) is created. You need it to ini­tial­ize the prop­er­ties of an object. The con­struc­tor es­sen­tial­ly defines the initial state of an instance. You can specify pa­ra­me­ters in the con­struc­tor to pass values when in­stan­ti­at­ing Type­Script classes.

The basic syntax of a con­struc­tor in Type­Script is:

class ClassName {
    constructor(parameter1: Type1, parameter2: Type2, ...) {
    }
}
type­script
  • con­struc­tor: Each class can have a single con­struc­tor. If no con­struc­tor is defined, an empty con­struc­tor is created by default.
  • parameter: Type: Pa­ra­me­ters are optional, depending on the class and its re­quire­ments. Pa­ra­me­ters should be labeled with their data types.

An example of a con­struc­tor:

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

In the example above, the Person class has a con­struc­tor that accepts two pa­ra­me­ters firstName and lastName. When creating an instance of this class, these pa­ra­me­ters are passed, and the con­struc­tor ini­tial­izes the firstName and lastName prop­er­ties of the instance with the cor­re­spond­ing values. this refers to the current instance of the class that the code is executed on.

Methods

In Type­Script, 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 {
    }
    // ...
}
type­script
  • method­Name: Name of the method
  • parameter: Type: Optional pa­ra­me­ters that the method accepts
  • Re­turn­Type: This is the data type that de­ter­mines 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 pa­ra­me­ters.

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();
type­script

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­ized in the con­struc­tor. The object person is created by the keyword new followed by the class name and the re­spec­tive pa­ra­me­ters. The method con­cate­nates the two strings when called and returns the full name as a string. The output for the object person is therefore “John Doe”.

Type­Script class examples

Type­Script classes have various mech­a­nisms to organize and control the structure and behavior of objects. Below, we present some concepts for using Type­Script classes.

Access

Type­Script 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­ces­si­ble 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­i­tance), 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();
type­script

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­i­tance

In­her­i­tance is a fun­da­men­tal concept in object-oriented pro­gram­ming (OOP) that is used in Type­Script 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();
type­script

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 behavior while in­her­it­ing the name property from Animal.

Readonly

You can use readonly to declare prop­er­ties of Type­Script classes or objects as read-only. This means that once a read-only property has been ini­tial­ized, 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
type­script

The pi property is read-only in our example and is ini­tial­ized in the con­struc­tor. After ini­tial­iza­tion, pi can no longer be changed. If you try to modify the value of pi after ini­tial­iza­tion, Type­Script will generate a com­pi­la­tion error.

$1 Domain Names – Register yours today!
  • Simple reg­is­tra­tion
  • Premium TLDs at great prices
  • 24/7 personal con­sul­tant included
  • Free privacy pro­tec­tion for eligible domains
Go to Main Menu