Pointers in TypeScript

TypeScript doesn’t have direct pointer manipulation like some lower-level languages. However, we can demonstrate similar concepts using object references. Here’s an equivalent example:

// We'll show how object references work in contrast to values with
// 2 functions: `zeroval` and `zeroref`. `zeroval` has a
// number parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
function zeroval(ival: number): void {
    ival = 0;
}

// `zeroref` in contrast has an object parameter with a
// number property. In TypeScript, objects are passed by reference.
// Modifying the object's property inside the function
// will affect the original object.
function zeroref(iobj: { value: number }): void {
    iobj.value = 0;
}

function main() {
    let i = 1;
    console.log("initial:", i);

    zeroval(i);
    console.log("zeroval:", i);

    // We create an object with a 'value' property to simulate
    // passing a reference to our number.
    let iobj = { value: i };
    zeroref(iobj);
    console.log("zeroref:", iobj.value);

    // In TypeScript, we can't print memory addresses,
    // but we can show that two variables reference the same object.
    let iobj2 = iobj;
    console.log("same reference:", iobj === iobj2);
}

main();

In this TypeScript example:

  1. We define zeroval which takes a number parameter. When we pass i to this function, it receives a copy of the value, so modifying it doesn’t affect the original i in main.

  2. We define zeroref which takes an object with a value property. In TypeScript (and JavaScript), objects are passed by reference. So when we modify iobj.value inside the function, it affects the original object.

  3. In the main function, we demonstrate both cases. We also show how to check if two variables reference the same object, which is somewhat analogous to comparing pointers in languages with explicit pointer syntax.

When you run this TypeScript code, you should see output similar to this:

initial: 1
zeroval: 1
zeroref: 0
same reference: true

This demonstrates that zeroval doesn’t change the i in main, but zeroref does because it has a reference to the object containing the value.

Note that TypeScript doesn’t have pointers in the same way as lower-level languages, but understanding object references is crucial for effective TypeScript programming.