Search code examples
jquerytypescriptinterfacees6-modules

How to extend JQuery functions in TypeScript


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?

enter image description here


Solution

  • 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