create an instance of a class with a constructor in typescript

To create an instance of a TypeScript class with a constructor, you can use the new keyword followed by the class name and constructor arguments in parentheses. Here's an example:

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

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

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

const person1 = new Person("John Doe", 30);
person1.sayHello(); // output: "Hello, my name is John Doe and I'm 30 years old."
367 chars
17 lines

In this example, we defined a class Person with a constructor that takes two arguments name and age. We then create an instance of Person by calling new Person("John Doe", 30) and assigning the result to the variable person1. Finally, we call the sayHello method on person1 to print a greeting message to the console.

Note that TypeScript supports both parameter properties (name: string in the class definition) and constructor parameter declarations (constructor(name: string, age: number)), both of which can be used to initialize class properties.

gistlibby LogSnag