2015-10-22 22 views
5

sto cercando di estendere l'interfaccia predefinita JQuery e l'oggetto di default jQuery da una funzione a macchinadattiloscritto estendere JQuery sotto Namespace

Codice

/// <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' }); 
    } 
} 

Il problema

Ora eseguo il seguente codice nella mia console: tsc -m amd -t ES5 Test.ts -d

sto ottenendo questo errore: Test.ts(17,19): error TS2339: Property 'test' does not exist on type 'JQuery'.

Qualsiasi soluzione per questo?

risposta

10

Questo funziona per me:

/// <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: 2 ° soluzione

/// <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' }); 
    } 
} 

si può fare il bello testBody da alcuni refactoring.

Problemi correlati