如何在TypeScript中扩展JQuery函数

问题描述:

我在TypeScript上重写了一些JS代码,并遇到模块导入问题。例如,我想写我的toggleVisiblity函数。这里是代码:如何在TypeScript中扩展JQuery函数

/// <reference path="../../typings/jquery/jquery.d.ts" /> 

import * as $ from "jquery"; 

interface JQuery { 
    toggleVisibility(): JQuery; 
} 

$.fn.extend({ 
    toggleVisibility: function() { 
     return this.each(function() { 
      const $this = $(this); 
      const visibility = $this.css('visibility') === 'hidden' ? 'visible' : 'hidden'; 
      $this.css('visibility', visibility); 
     }); 
    } 
}); 

const jQuery = $('foo'); 
const value = jQuery.val(); 
jQuery.toggleVisibility(); 

但问题是,由于未知原因,toggleVisibility不添加到JQuery界面就我得到一个错误Property 'toggleVisibility' does not exist on type 'JQuery'.,尽管它看到其他的方法(valeach等)。

为什么它不起作用?

enter image description here

+0

看来你的界面'JQuery'不与原来的合并。也许它应该被导入。你是如何导入jQuery的定义的?有了新的_ @ types_系统? – Paleo

+0

@Paleo with'tsd install jQuery --save' afair –

尝试把

interface JQuery { 
    toggleVisibility(): JQuery; 
} 

里面一个单独的文件,而无需导入/导出报表。 这适用于我。尽管知道原因很有趣。

编辑:对于这种行为在这个职位一个很好的解释: How to extend the 'Window' typescript interface

+0

我将在TS github中创建一个问题,也许它会被修复。谢谢你的回答。 –

+0

@AlexZhukovskiy请给出问题的链接,我也很感兴趣。 – Paleo

+1

@Paleo https://github.com/Microsoft/TypeScript/issues/12648 –

我得到了解决,这个工作对我来说:

使用JQueryStatic界面类似$静态jQuery的访问.jGrowl(...)或jQuery.jGrowl(...),或在你的情况,jQuery.toggleVisibility():

interface JQueryStatic { 

    ajaxSettings: any; 

    jGrowl(object?, f?): JQuery; 

} 

并为自己的定制功能,您使用u星1.3中,使用JQuery的界面:

interface JQuery { 

    fileinput(object?): void;//custom jquery plugin, had no typings 

    enable(): JQuery; 

    disable(): JQuery; 

    check(): JQuery; 

    select_custom(): JQuery; 

} 

可选,这里有我的扩展jQuery函数:

jQuery.fn.extend({ 
    disable: function() { 
     return this.each(function() { 
      this.disabled = true; 
     }); 
    }, 
    enable: function() { 
     return this.each(function() { 
      this.disabled = false; 
     }); 
    }, 
    check: function (checked) { 
     if (checked) { 
      $(this).parent().addClass('checked'); 
     } else { 
      $(this).parent().removeClass('checked'); 
     } 
     return this.prop('checked', checked); 
    }, 
    select_custom: function (value) { 
     $(this).find('.dropdown-menu li').each(function() { 
      if ($(this).attr('value') == value) { 
       $(this).click(); 
       return; 
      } 
     }); 
    } 
});