在打字稿函数中声明“this"的类型? [英] Declaring the type of 'this' in a typescript function?
问题描述
我正在用 TypeScript 编写一个 grunt 任务.我正在尝试翻译我在 JavaScript 中已有的东西.
I'm writing a grunt task in TypeScript. I'm trying to translate something I already have in JavaScript.
所以,当 grunt 运行一个任务时,它运行一个函数.当它运行时,grunt 将 this
设置为一个具有有用属性的对象,就像 jQuery 用你正在处理的元素重载 this
一样.我可以访问有用的属性,例如 this.files
;
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); });
});
所以,删除this.files
中的所有文件".
So, "delete all the files in this.files
".
但是,在 TypeScript 中,我不知道您是否可以暗示"编译器 this
是一种特定类型,因此我没有得到智能感知.我如何告诉 TypeScript 将 this
视为不同的类型?
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?
推荐答案
我如何告诉 TypeScript 将其视为不同的类型
How do I tell TypeScript to consider this to be a different type
您可以通过声明一个 this
参数来做到这一点.对于您的用例,我添加了 this: {files:any[]}
:
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); });
});
更多
- 关于
this
参数
这篇关于在打字稿函数中声明“this"的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!