create an instance of a class in typescript

To create an instance of a class in TypeScript, first, you'll need to define the class. Here's an example class with a constructor:

index.ts
class MyClass {
  constructor(public myProperty: string) {}
  
  myMethod(): string {
    return 'Hello from MyClass';
  }
}
125 chars
8 lines

In the example above, the MyClass has a single property, myProperty, and a method, myMethod.

Now, to create an instance of the MyClass, you just need to use the new keyword and pass any necessary arguments to the constructor:

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

In this example, we create a new instance of MyClass called myInstance with the property value of 'hello world'.

You can now call the myMethod on this instance:

index.ts
const message = myInstance.myMethod();
console.log(message); // output: "Hello from MyClass"
93 chars
3 lines

And you can access the myProperty property:

index.ts
console.log(myInstance.myProperty); // output: "hello world"
61 chars
2 lines

gistlibby LogSnag