【问题标题】:Declaring the type of 'this' in a typescript function?在打字稿函数中声明“this”的类型?
【发布时间】:2015-03-07 22:24:38
【问题描述】:

我正在用 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 是一种特定类型,所以我没有智能感知。如何告诉 TypeScript 将 this 视为不同的类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

    this 参数是函数参数列表中最先出现的假参数

    更多信息here

    【讨论】:

    【解决方案2】:

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

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

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

    更多

    【讨论】:

      【解决方案3】:

      虽然我发现现在可以这样做:

      class ClassyClass {
          prop = 'Juicy Strings'
      }
      
      function x( this: ClassyClass ) {
          console.log( this.prop )
      }
      

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

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

      【讨论】:

      • 或者你可以使用多行函数参数;)
      【解决方案4】:

      我有一点答案。我可以这样做;

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

      这工作正常。它会产生后果,比如无法编写箭头函数......

      【讨论】:

      • 您仍然可以编写箭头函数,因为它们将关闭self 变量。箭头函数中的this 仍然会打错,但至少可以省下几个字符!
      猜你喜欢
      • 2019-05-05
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多