add a method to a class in typescript

To add a method to a class in TypeScript, you can do so by adding the method to the class's prototype property. Here's an example:

index.ts
class Example {
  private message: string;

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

  public sayHello(): void {
    console.log(`Hello ${this.message}!`);
  }
}

Example.prototype.sayGoodbye = function(): void {
  console.log(`Goodbye ${this.message}!`);
};
284 chars
16 lines

In this example, sayGoodbye is added as a method to the Example class's prototype property. You can also add methods directly to the class itself using the static keyword:

index.ts
class Example {
  private static count: number = 0;

  constructor() {
    Example.count++;
  }

  public static getCount(): number {
    return Example.count;
  }
}
166 chars
12 lines

In this example, getCount is added as a static method to the Example class. You can call it directly on the class itself without needing an instance of the class.

gistlibby LogSnag