是否可以使用TypeScript对jQuery.fn.extend建模 [英] Is it possible to model jQuery.fn.extend using TypeScript

查看:76
本文介绍了是否可以使用TypeScript对jQuery.fn.extend建模的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My guess is that the answer to this is "no" but I wanted to check there wasn't something I'd missed.

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

jQuery has a fn.extend method which allows you to augment the jQuery object with extra methods. Here's an example from the API docs:

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();

我一直在填写jQuery JSDoc并测试DefinitelyTyped 项目。以前jQuery.fn被定义为 any 。为了使它与我一直在寻找的文档保持一致,以覆盖 extend 方法:

I've been filling out the jQuery JSDoc and tests for the DefinitelyTyped project. Previously jQuery.fn was defined as any. To bring it in line with the docs I've been looking at changing it to cover the extend method:

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;
}

但是,我认为TypeScript中没有办法对 dynamic 而不是 static 方法的扩充。这意味着你不可能随后在你的TS中使用这些动态增强的方法,除非你:

However, I don't think there's a way in TypeScript to model the dynamic rather than static augmentation of methods. This means it's not possible to subsequently use these dynamically augmented methods in your TS unless you either:


  1. 将jQuery强制转换为任何

  2. 使用括号表示法,如 $(input [type ='checkbox'])[check]() ;

  1. cast jQuery to any or
  2. use bracket notation like $("input[type='checkbox']")["check"]();

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

So my question: is there something I've missed? Is there a better way to model jQuery.fn so TypeScript can pick up that jQueryStatic gets assigned these dynamic methods? As I say, I think the answer is "no" but I wanted to be sure.

推荐答案

这是一个明确的否定。

It is a definitive no.

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

It would be nice to execute code in the compiler inside the definition but no such syntax exists. This is what I wish it had:


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.
   }
}

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

But it has the potential of making the compilation slow, and would be full of edge cases, not to mention its more work that isn't on the table I presume.

这篇关于是否可以使用TypeScript对jQuery.fn.extend建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆