I'm rewriting some JS code on TypeScript and encounter with problems with module import. For example, I want to write my toggleVisiblity
function. Here is 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
is not added to JQuery
interface thus I get an error Property 'toggleVisibility' does not exist on type 'JQuery'.
, although it sees other methods (val
, each
and so on).
Why is it not working?
jQuery | extend() method This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object. Parameters: The extend() method accepts four parameter that is mentioned above and described below: deep: This parameter is the merge becomes recursive .
fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn. something = function{}
extend() method is used to merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. Syntax: jQuery.fn.extend( object )
Try putting the
interface JQuery {
toggleVisibility(): JQuery;
}
Inside a seperate file without import/export statements. This works for me. Though it wold be interesting to know why.
EDIT: There is an excellent explanation for this behaviour in this answer to post: How to extend the 'Window' typescript interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With