2015-10-22 50 views
5

Tôi đang cố gắng để mở rộng giao diện mặc định JQuery và đối tượng mặc định jQuery bởi một hàm trong nguyên cảonguyên cảo mở rộng JQuery dưới Namespace

/// <reference path="jquery.d.ts" /> 

namespace MyNameSpace { 
    var $ = jQuery; 
    export interface JQuery { 
     test(options: Object): JQuery; 
    } 
    $.fn.test = function(options: Object): JQuery { 
     if (this.length === 0) { 
      console.log('Error!'); 
      return this; 
     } 
     console.log(options); 
     return this; 
    } 
    export var testBody = function() { 
     jQuery('body').test({ 'HELLO': 'TEST' }); 
    } 
} 

Vấn đề

Bây giờ tôi đang chạy mã sau trong bảng điều khiển của tôi: tsc -m amd -t ES5 Test.ts -d

Tôi gặp phải lỗi này: Test.ts(17,19): error TS2339: Property 'test' does not exist on type 'JQuery'.

Bất kỳ giải pháp nào cho điều này?

Trả lời

10

này làm việc cho tôi:

/// <reference path="typings/jquery/jquery.d.ts" /> 

interface JQuery { 
    test(options: Object): JQuery; 
} 

namespace MyNameSpace { 
    var $ = jQuery; 

    $.fn.test = function(options: Object): JQuery { 
     if (this.length === 0) { 
      console.log('Error!'); 
      return this; 
     } 
     console.log(options); 
     return this; 
    }; 
    export var testBody = function() { 
     jQuery('body').test({ 'HELLO': 'TEST' }); 
    } 
} 

EDIT: giải pháp thứ 2

/// <reference path="typings/jquery/jquery.d.ts" /> 

namespace MyNameSpace { 

    interface JQueryX extends JQuery { 
     test(options: Object): JQuery; 
    } 

    $.fn.test = function(options: Object): JQuery { 
     if (this.length === 0) { 
      console.log('Error!'); 
      return this; 
     } 
     console.log(options); 
     return this; 
    }; 

    export var testBody = function() { 
     let a:JQueryX = <JQueryX>$('body'); 
     a.test({ 'HELLO': 'TEST' }); 
     // OR 
     (<JQueryX>$('body')).test({ 'HELLO': 'TEST' }); 
    } 
} 

Bạn có thể làm cho testBody đẹp hơn bởi một số refactoring.