classes in typescript

Creating classes in TypeScript is similar to creating classes in other object-oriented programming languages. To create a class, use the class keyword followed by the class name. Inside the class, you can declare properties, methods and constructors.

Here's an example of a simple class in TypeScript:

index.ts
class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

let john = new Person("John Doe", 25);
john.sayHello(); // output: "Hello, my name is John Doe and I'm 25 years old."
359 chars
17 lines

In the example above, we created a class Person with two properties name and age. We also declared a constructor that accepts name and age parameters and assigns them to object properties. Finally, we created a method sayHello that logs a message to the console using object properties.

To create an object of a class, use the new keyword followed by the class name and constructor arguments. In the example above, we created an object john of the Person class using the new keyword and passed "John Doe" and 25 as constructor arguments.

We could extend the Person class to create a Student class as below:

index.ts
class Student extends Person {
    grade: number;

    constructor(name: string, age: number, grade: number) {
        super(name, age);
        this.grade = grade;
    }

    study() {
        console.log(`${this.name} is studying.`);
    }
}

let jane = new Student("Jane Smith", 20, 4);
jane.sayHello(); // output: "Hello, my name is Jane Smith and I'm 20 years old."
jane.study(); // output: "Jane Smith is studying."
422 chars
17 lines

In the example above, we extended the Person class to create a Student class. We added a new property grade, declared a new constructor that calls the base class constructor using the super keyword, and a new method study.

We created an object jane of the Student class using the extended constructor and accessed the sayHello method from the base class as well as the study method from the derived class.

That's the basics of classes in TypeScript.

gistlibby LogSnag