Methods in TypeScript

TypeScript supports methods defined on class types. Here’s an example:

class Rect {
    constructor(public width: number, public height: number) {}

    // This `area` method is defined on the `Rect` class.
    area(): number {
        return this.width * this.height;
    }

    // Methods can be defined directly in the class.
    perim(): number {
        return 2 * this.width + 2 * this.height;
    }
}

function main() {
    const r = new Rect(10, 5);

    // Here we call the 2 methods defined for our class.
    console.log("area: ", r.area());
    console.log("perim:", r.perim());

    // TypeScript automatically handles method calls on class instances.
    // There's no need to worry about pointer vs value semantics as in some other languages.
    // All non-primitive types in TypeScript are reference types.
    const rRef = r;
    console.log("area: ", rRef.area());
    console.log("perim:", rRef.perim());
}

main();

To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:

$ tsc methods.ts
$ node methods.js
area:  50
perim: 30
area:  50
perim: 30

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.