簡體   English   中英

從jquery TypeScript定義文件中缺少.top?

[英].top missing from jquery TypeScript definition files?

我使用以下代碼:

$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });

打字稿給我一條錯誤信息說:

The property 'top' does not exist on value of type 'Object'

我猜jQuery定義文件中缺少某些東西。 有沒有其他人看到這個問題,或者這是通常不與jQuery一起使用的東西? 這是我以前沒見過的東西。

欲獲得更多信息。 以下是使用它的代碼:

   $.fn.buildTableOfContent = function () {
        "use strict";
        var h2 = this.find('h2');
        if (h2.length > 0) {
            var h1 = this.find('h1:first');
            if (h1.length === 0) {
                h1 = this.prepend('<h1>Help</h1>').children(':first');
            }
            var menu = h1.wrap('<div class="h1 with-menu"></div>')
                    .after('<div class="menu"><img src="/Content/images/menu-open-arrow.png" width="16" height="16"><ul></ul></div>')
                    .next().children('ul');
            h2.each(function (i) {
                this.id = 'step' + i;
                menu.append('<li class="icon_down"><a href="#step' + i + '">' + $(this).html() + '</a></li>');
            });
            menu.find('a').click(function (event) {
                event.preventDefault();
                $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });
            });
        }
        return this;
    };

從jquery.d.ts文件(我的版本中的第374行):

interface JQuery {
   ...
   offset(): Object;
   offset(coordinates: any): JQuery;
   offset(func: (index: any, coords: any) => any): JQuery;
   ...
}

通過調用沒有參數的函數,類型定義要求函數返回Object類型。 我查看了jQuery的文檔,你是對的,返回的對象應該有topleft屬性。

不幸的是,由於沒有基於返回類型的重載這樣的東西,你將無法在JQuery接口上添加另一個成員。 因為,在這種特殊情況下,類型定義根本不是特定的,我建議只修改你的jquery.d.ts文件並更改返回類型,使其看起來如下(可能是字符串而不是數字?):

offset(): { top : number; left : number; };

如果您不想修改此文件,您還可以選擇在訪問任何屬性之前將結果轉換為any ,例如:

$('html, body').animate({ scrollTop: (<any> $($(this).attr('href')).offset()).top });

缺點是每次調用沒有參數的函數時都需要強制轉換。

而不是這個

 $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });

嘗試這個

 $('html, body').animate({ scrollTop: $(this).offset().top });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM