如何在TypeScript中扩展JQuery函数

问题描述 投票:0回答:3
jquery typescript interface es6-modules
3个回答
38
投票

尝试将

interface JQuery {
    toggleVisibility(): JQuery;
}

在没有导入/导出语句的单独文件内。 这对我有用。虽然知道为什么会很有趣。

编辑:在此帖子的答案中对此行为有很好的解释: 如何扩展“Window”打字稿接口


10
投票

我找到了解决方案,这对我有用:

使用 JQueryStatic 接口进行静态 jQuery 访问,例如 $.jGrowl(...) 或 jQuery.jGrowl(...) 或者在您的情况下,jQuery.toggleVisibility():

interface JQueryStatic {

    ajaxSettings: any;

    jGrowl(object?, f?): JQuery;

}

对于您使用 jQuery.fn.extend 使用的自定义函数,请使用 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;
            }
        });
    }
});

0
投票

我遇到了类似的问题,但我的 bootstrapDP 函数以相同的方式扩展了 JQuery。

解决方案:

    declare global {
        interface JQuery {
            bootstrapDP: any;
        }
    }

解释

此代码声明了 JQuery 接口的全局增强,并向其中添加了我的 bootstrapDP 方法。添加此代码后,TypeScript 应该将 bootstrapDP 识别为 jQuery 对象上的方法。

这里是一些有关全局认证的文档:link

© www.soinside.com 2019 - 2024. All rights reserved.