create a class with a constructor in typescript

To create a class with a constructor in TypeScript, you can use the following syntax:

index.ts
class MyClass {
  constructor(parameter1: type1, parameter2: type2) {
    // constructor code goes here
  }
}
110 chars
6 lines

In the example above, MyClass is the name of the class, and parameter1 and parameter2 are the constructor parameters with their respective types type1 and type2. You can add more parameters separated by commas if needed.

The constructor code goes inside the curly braces {} after the constructor declaration. This code executes whenever you create a new instance of the class using the new keyword.

Here's an example of how to create a Person class with a constructor that sets the name and age properties:

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

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
138 chars
10 lines

In the example above, we declare two properties name and age of types string and number respectively. We then use the constructor to set these properties whenever we create a new Person object.

index.ts
Note: TypeScript is a superset of JavaScript that adds static types and other features to the language. To use TypeScript, you must install it globally or locally in your project using NPM.
190 chars
2 lines

gistlibby LogSnag