20

我在 TypeScript 上重写了一些 JS 代码,遇到了模块导入问题。例如,我想编写我的toggleVisiblity函数。这是代码:

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

但问题是由于未知原因toggleVisibility没有添加到JQuery接口中,因此我得到一个错误Property 'toggleVisibility' does not exist on type 'JQuery'.,尽管它看到了其他方法(val等等each)。

为什么它不起作用?

在此处输入图像描述

4

2 回答 2

36

尝试将

interface JQuery {
    toggleVisibility(): JQuery;
}

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

编辑:在这个帖子的答案中有一个很好的解释: 如何扩展“窗口”打字稿界面

于 2016-12-04T10:08:02.423 回答
6

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

使用 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;
            }
        });
    }
});
于 2017-11-03T08:43:06.640 回答