Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend JQuery functions in TypeScript

Tags:

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

like image 324
Alex Zhukovskiy Avatar asked Dec 03 '16 13:12

Alex Zhukovskiy


People also ask

How to extend function in jQuery?

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 .

What does fn mean jQuery?

fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn. something = function{}

What is FN extend?

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 )


1 Answers

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

like image 65
mode777 Avatar answered Oct 21 '22 09:10

mode777