2016-12-03 9 views
6

TypeScript에서 일부 JS 코드를 다시 작성하고 모듈 가져 오기와 관련된 문제가 발생합니다. 예를 들어, 내 toggleVisiblity 함수를 작성하고 싶습니다. 여기에 코드입니다 :TypeScript에서 JQuery 함수를 확장하는 방법

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

그러나 문제는 알 수없는 이유로 toggleVisibilityJQuery 인터페이스에 추가되지 않은 것이 다른 방법 (val, each 등)를 볼 수 있지만, 따라서 나는 오류 Property 'toggleVisibility' does not exist on type 'JQuery'.를 얻을 수 있다는 것입니다.

왜 작동하지 않습니까?

enter image description here

+0

그것은 당신의 인터페이스'JQuery'이 원래와 통합되지 않은 것 같다. 어쩌면 그것이 수입되어야합니다. jQuery에 대한 정의를 어떻게 가져 왔습니까? 새로운 _ @ types_ 시스템으로? – Paleo

+0

@Paleo with'tsd install jQuery --save' afair –

답변

11

가져 오기/내보내기 문 않고 별도의 파일 안에는

interface JQuery { 
    toggleVisibility(): JQuery; 
} 

을 넣어보십시오. 나를 위해 작동합니다. 이유를 아는 것이 재미있을지라도.

편집 : How to extend the 'Window' typescript interface

+0

TS github에서 문제를 만들겠습니다. 아마도 수정 될 것입니다. 답변 해 주셔서 감사합니다. –

+0

@AlexZhukovskiy 문제에 대한 링크를 제공해주십시오. 나도 관심이 있습니다. – Paleo

+1

@Paleo https://github.com/Microsoft/TypeScript/issues/12648 –

1

나는 해결책을 가지고, 이것은 나를 위해 일한 : $ 같은 정적 jQuery를 액세스

사용 JQueryStatic 인터페이스이 게시물에서이 문제에 대한 훌륭한 설명이 있습니다 .jGrowl (...) 또는 jQuery.jGrowl (...) 또는 귀하의 경우, jQuery.toggleVisibility() :

interface JQueryStatic { 

    ajaxSettings: any; 

    jGrowl(object?, f?): JQuery; 

} 

그리고 자신 만의 맞춤 제작 한 기능

당신은 U를 사용 노래 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; 
      } 
     }); 
    } 
});