在打字稿函数中声明 'this' 的类型?

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

我正在用 TypeScript 编写 grunt task。我正在尝试翻译 JavaScript 中已有的内容。

所以,当 grunt 运行一个任务时,它运行一个函数。运行时,grunt 将 this 设置为具有有用属性的对象,与 jQuery 重载 this 与您正在处理的元素的方式相同。我可以访问有用的属性,例如 this.files;

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

所以,"delete all the files in this.files".

但是,在 TypeScript 中,我不知道您是否可以 'hint' 向编译器表明 this 是一种特定类型,所以我没有得到智能感知。我如何告诉 TypeScript 将 this 视为不同的类型?

我有点答案了。我可以做到;

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

});

效果不错。它会产生后果,比如无法编写箭头函数...

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

您可以通过声明一个 this 参数来做到这一点。对于您的用例,我添加了 this: {files:any[]}:

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

更多

现在(从 TS 2.0 开始)您可以使用 fake this 参数(应该是第一个)指定函数的 this 类型:

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

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

更多信息here

虽然我发现现在可以用这个:

class ClassyClass {
    prop = 'Juicy Strings'
}

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

我更喜欢在参数行中不占用空间的替代方案

function x() {
    const that: ClassyClass = this

    console.log( that.prop )
}