是否可以使用TypeScript对jQuery.fn.extend建模

Joh*_*lly 7 jquery typescript

我的猜测是,答案是"不",但我想检查一下我没有错过的东西.

jQuery有一个fn.extend方法,它允许你用额外的方法扩充jQuery对象.以下是API文档中的示例:

jQuery.fn.extend({
  check: function() {
    return this.each(function() {
      this.checked = true;
    });
  },
  uncheck: function() {
    return this.each(function() {
      this.checked = false;
    });
  }
});

// Use the newly created .check() method
$( "input[type='checkbox']" ).check();
Run Code Online (Sandbox Code Playgroud)

我一直在填写jQuery JSDoc并测试DefinitelyTyped项目.以前jQuery.fn被定义为any.为了使它符合我一直在寻找的文档更改它以涵盖extend方法:

fn: {
    /**
     * Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.
     * 
     * @param object An object to merge onto the jQuery prototype.
     */
    extend(object: any): any;
}
Run Code Online (Sandbox Code Playgroud)

但是,我认为TypeScript中没有一种方法可以模拟动态而非静态的方法扩充.这意味着您无法在TS中随后使用这些动态增强方法,除非您:

  1. 将jQuery转换为any
  2. 使用括号表示法 $("input[type='checkbox']")["check"]();

所以我的问题是:有什么我错过了吗?有没有更好的模型方法,jQuery.fn因此TypeScript可以jQueryStatic获取分配这些动态方法?正如我所说,我认为答案是"不",但我想确定.

bas*_*rat 3

这是一个明确的否定。

在定义内的编译器中执行代码会很好,但不存在这样的语法。这就是我希望它有的:


interface Foo{
   bar(member:any):any @ execute { // execute this code inside the compiler language service:
       var keys = compiler.getArgs().keys();
       compiler.getIdentifier('JQueryStatic').addMembers /// you get the point.
   }
}
Run Code Online (Sandbox Code Playgroud)

但它有可能使编译速度变慢,并且会充满边缘情况,更不用说我认为它不存在的更多工作了。