声明'这个'在打字稿功能?

时间:2015-03-07 22:24:39

标签: typescript

我正在使用TypeScript编写grunt task。我正在尝试翻译我在JavaScript中已有的东西。

因此,当grunt运行任务时,它会运行一个函数。当它运行时,grunt将this设置为具有有用属性的对象,就像jQuery使用您正在处理的元素重载this一样。我可以访问有用的属性,如this.files;

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

所以,“删除this.files”中的所有文件。

但是,在TypeScript中,我不知道你是否可以“提示”this是特定类型的编译器,所以我没有得到intellisense。如何告诉TypeScript将this视为不同的类型?

5 个答案:

答案 0 :(得分:32)

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

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

更多信息here

答案 1 :(得分:5)

此功能现在可在TS 2.0中使用。请参阅https://github.com/Microsoft/TypeScript/pull/6739

答案 2 :(得分:1)

  

如何告诉TypeScript将其视为不同的类型

目前还没有专门的语法,但有关于它的讨论:https://github.com/Microsoft/TypeScript/issues/229

现在你所做的实际上是唯一的方法,虽然我不会使用断言而只是使用类型注释:

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

});

答案 3 :(得分:1)

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

class ClassyClass {
    prop = 'Juicy Strings'
}

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

我更喜欢在参数行中不占用房地产的替代方案

function x() {
    const that: ClassyClass = this

    console.log( that.prop )
}

答案 4 :(得分:0)

我有点答案。我能做到这一点;

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

});

哪个有效。它会产生后果,比如无法编写箭头功能......

相关问题