123

I'm writing a grunt task in TypeScript. I'm trying to translate something I already have in JavaScript.

So, when grunt runs a task, it runs a function. When it runs, grunt sets this to an object with useful properties, the same way that jQuery overloads this with the element you are working on. I could access useful properties like this.files;

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

So, "delete all the files in this.files".

However, in TypeScript, I don't know if you can 'hint' to the compiler that this is a particular type, so I don't get intellisense. How do I tell TypeScript to consider this to be a different type?

4 Answers 4

168

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

Sign up to request clarification or add additional context in comments.

3 Comments

'This' fake argument is a really hard thing to google for!
Seeing this (excuse the pun) and thinking its pure Voodoo =)
56

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

Comments

3

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 )
}

3 Comments

Or you could use multi-line function parameters ;)
Using that feels most clean to me as well. TY @Jason. Throwback. I recall back in the jQuery days doing a lot of that = this;
If you put it in the parameters doesn't that add typechecking when you call the function? So that would be the stricter solution?
0

I have a bit of an answer. I can do this;

var self = <grunt.task.IMultiTask<string>>this;
self.files.forEach(function (f) {

});

which works OK. It's gonna have consequences, like not being able to write arrow functions...

1 Comment

You an still write arrow functions, since they will close over the self variable. this in the arrow functions will still be incorrectly typed, but at least you can save a few characters!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.