create a class in typescript

To create a class in TypeScript:

index.ts
class MyClass {
  public property1: string;
  private property2: number;

  constructor(prop1: string, prop2: number){
    this.property1 = prop1;
    this.property2 = prop2;
  }

  public myMethod(arg1: number): void {
    console.log(`Property 1: ${this.property1}`);
    console.log(`Property 2: ${this.property2}`);
    console.log(`Argument 1: ${arg1}`);
  }
}

let myInstance = new MyClass("Hello", 123);
myInstance.myMethod(456);
437 chars
19 lines

In this example, we have defined a class named MyClass with a public property1 of type string and a private property2 of type number. Additionally, we have defined a constructor that takes two arguments and initializes both properties. We have also defined a method named myMethod that takes a number argument and logs the values of both properties and the argument to the console.

We then create an instance of the class by invoking the constructor with the new keyword and passing the required arguments. Finally, we call the myMethod method on the instance, passing a number argument.

Note that TypeScript supports both public, private, and protected access modifiers for class members, as well as readonly properties. Additionally, TypeScript supports class inheritance and interface implementation, which allow for powerful object-oriented programming constructs.

gistlibby LogSnag