Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring the type of 'this' in a typescript function?

Tags:

typescript

Now (from TS 2.0) you can specify function's this type by using fake this parameter (should be the first one):

grunt.registerMultiTask('clean', function(this: SomeType) {
    //...
});

this parameters are fake parameters that come first in the parameter list of a function

More info here


How do I tell TypeScript to consider this to be a different type

You can do that by declaring a this parameter. For your use case I've added this: {files:any[]}:

grunt.registerMultiTask('clean', function(this: {files:any[]}) {
    this.files.forEach(function(f) { Delete(f); });
});

More

  • Official docs on this parameter

While I found that is now possible with this:

class ClassyClass {
    prop = 'Juicy Strings'
}

function x( this: ClassyClass ) {
    console.log( this.prop )
}

I have come prefer an alternative that doesn't take up real estate in the arguments line

function x() {
    const that: ClassyClass = this

    console.log( that.prop )
}