如何在 TypeScript 中扩展 JQuery 函数 [英] How to extend JQuery functions in TypeScript

查看:35
本文介绍了如何在 TypeScript 中扩展 JQuery 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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).

为什么它不起作用?

推荐答案

尝试放置

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:在这个帖子中对这种行为有一个很好的解释:如何扩展Window"打字稿界面

EDIT: There is an excellent explanation for this behaviour in this answer to post: How to extend the 'Window' typescript interface

这篇关于如何在 TypeScript 中扩展 JQuery 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆