Close

TypeScript - 'this' Parameter in functions

[Updated: Sep 25, 2018, Created: Sep 24, 2018]

In the last tutorial we saw how to avoid wrong use of 'this'.

TypeScript also allows to explicitly specify the type of 'this'. This way we can tell the compiler that what the intended type of 'this' will be during execution time.

Without 'this' parameter

Consider the following example:

class Rectangle {
    private w;
    private h;

    constructor(w, h) {
        this.w = w;
        this.h = h;
    }

    getAreaFunction() {
        return () => {
            return this.w * this.h;
        }
    }
}

With 'this' parameter

class Rectangle {
    private w;
    private h;

    constructor(w, h) {
        this.w = w;
        this.h = h;
    }

    getAreaFunction(this: Rectangle) {
        return () => {
            return this.w * this.h;
        }
    }
}

Preventing use of 'this'

To prevent the use of 'this' in a function we can use this: void parameter:

class Rectangle {
    private w;
    private h;

    constructor(w, h) {
        this.w = w;
        this.h = h;
    }

    getAreaFunction(this: void) {
        return () => {
            return this.w * this.h;
        }
    }
}

Output

function-with-this-void-param.ts(12,25): error TS2339: Property 'w' does not exist on type 'void'.
function-with-this-void-param.ts(12,34): error TS2339: Property 'h' does not exist on type 'void'.

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.3
Understanding 'this' parameters Select All Download
  • typescript-function-this-parameter
    • function-with-this-param.ts

    See Also