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.ts367 chars17 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