To create a class with a constructor in TypeScript, you can use the following syntax:
index.ts110 chars6 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.ts138 chars10 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.ts190 chars2 lines
gistlibby LogSnag