Creating classes in TypeScript is similar to creating classes in other object-oriented programming languages. To create a class, use the class keyword followed by the class name. Inside the class, you can declare properties, methods and constructors.
Here's an example of a simple class in TypeScript:
index.ts359 chars17 linesIn the example above, we created a class Person with two properties name and age. We also declared a constructor that accepts name and age parameters and assigns them to object properties. Finally, we created a method sayHello that logs a message to the console using object properties.
To create an object of a class, use the new keyword followed by the class name and constructor arguments. In the example above, we created an object john of the Person class using the new keyword and passed "John Doe" and 25 as constructor arguments.
We could extend the Person class to create a Student class as below:
index.ts422 chars17 linesIn the example above, we extended the Person class to create a Student class. We added a new property grade, declared a new constructor that calls the base class constructor using the super keyword, and a new method study.
We created an object jane of the Student class using the extended constructor and accessed the sayHello method from the base class as well as the study method from the derived class.
That's the basics of classes in TypeScript.
gistlibby LogSnag