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

前端 未结 4 1156
盖世英雄少女心
盖世英雄少女心 2020-12-01 17:32

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 ru

相关标签:
4条回答
  • 2020-12-01 18:21

    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...

    0 讨论(0)
  • 2020-12-01 18:24

    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

    0 讨论(0)
  • 2020-12-01 18:31

    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 )
    }
    
    0 讨论(0)
  • 2020-12-01 18:33

    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
    0 讨论(0)
提交回复
热议问题