define a class in typescript

To define a class in TypeScript, use the class keyword followed by the class name. A class can have properties, methods, and a constructor.

index.ts
class MyClass {
  myProperty: string;
  
  constructor(myParameter: string) {
    this.myProperty = myParameter;
  }
  
  myMethod() {
    console.log('Hello from myMethod!');
  }
}
182 chars
12 lines

In the above example, we define a class MyClass with a property myProperty, a constructor that accepts a parameter myParameter, and a method myMethod. Inside the constructor, we set the value of myProperty to the value of myParameter.

To create an instance of the class, use the new keyword followed by the class name and the necessary arguments:

index.ts
const myInstance = new MyClass('Hello World');
47 chars
2 lines

This creates a new instance of MyClass with myProperty set to the value 'Hello World'. You can then call its methods like this:

index.ts
myInstance.myMethod(); // output: Hello from myMethod!
55 chars
2 lines

gistlibby LogSnag