In typescript, we can declare methods inside a class using the following syntax:

class Myclass {
  myMethod() {}
}

Let’s say we have a class Student and we want a method that greets a student. To do so we can declare a greet() method as follows.

class Student {
  greet() {
    console.log("Hello!");
  }
}

let student = new Student();

console.log(student.greet()); // Hello!

To call the method, we first create an object student and call the method using student.greet().

Passing parameters

We can also pass parameters to the method. For example,

class Student {
  greet(msg: string) {
    console.log(msg);
  }
}

let student = new Student();

console.log(student.greet("Hi")); // Hi

In this example, the greet() method takes a single parameter msg of type string and logs the output.

Using this keyword in methods

We can also access the properties of a class inside the method using the this keyword. Suppose we want the greet() method to display the name of the student along with the message. We can do so by creating a property name and using this.name within the method.

class Student {
  name: string;

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

  greet() {
    console.log(`Hello ${this.name}`);
  }
}

let student = new Student("Bob");

console.log(student.greet()); // Hello Bob

Depending on the context, the value of this can change. We can pass this as a parameter in the greet() method which tells the TypeScript what the value of this should be. The type of this in our example is Student.

class Student {
  name: string;

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

  greet(this: Student) {
    console.log(`Hello ${this.name}`);
  }
}

let student = new Student("Bob");

student.greet(); // Hello Bob