Methods in TypeScript
TypeScript supports methods defined on class types. Here’s an example:
To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:
In TypeScript, classes are used to create objects that have both data and methods. The class
keyword is used to define a class, and the constructor
method is used to initialize new instances of the class.
Methods in TypeScript are simply functions that are part of a class. They can access the class’s properties using the this
keyword.
Unlike some other languages, TypeScript (and JavaScript) don’t have a concept of value vs reference types for objects. All objects, including instances of classes, are reference types. This means you don’t need to worry about pointer vs value semantics when calling methods.
Next, we’ll look at TypeScript’s mechanism for defining contracts for classes: interfaces.