How to extend jQuery functions in TypeScript

I am rewriting JS code in TypeScript and am having problems importing the module. For example, I want to write my toggleVisiblity function. Here is the code:

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

But the problem is that for unknown reason, toggleVisibility not added to the JQuery interface, so I get the error Property 'toggleVisibility' does not exist on type 'JQuery'. although he sees other methods ( val , each , etc.).

Why doesn't it work?

enter image description here

+6
source share
2 answers

Try to put

 interface JQuery { toggleVisibility(): JQuery; } 

Inside a single file without import / export instructions. This works for me. Although it’s interesting to know why.

EDIT . This post has a great explanation of this behavior: How to extend the 'Window' typescript interface

+11
source

I got a solution, this worked for me:

Use the JQueryStatic interface to statically access jQuery, for example $ .jGrowl (...) or jQuery.jGrowl (...) or in your case jQuery.toggleVisibility ():

 interface JQueryStatic { ajaxSettings: any; jGrowl(object?, f?): JQuery; } 

And for your own custom functions that you use with jQuery.fn.extend, use the jQuery interface:

 interface JQuery { fileinput(object?): void;//custom jquery plugin, had no typings enable(): JQuery; disable(): JQuery; check(): JQuery; select_custom(): JQuery; } 

Additionally, here are my advanced jQuery features:

 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; } }); } }); 
+1
source

Source: https://habr.com/ru/post/1012860/


All Articles