사용자 도구

사이트 도구


typescript:function

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
typescript:function [2019/07/27 16:06] – [this parameters in callbacks] taekgutypescript:function [2025/04/15 10:05] (현재) – 바깥 편집 127.0.0.1
줄 67: 줄 67:
 let myAdd = function(x: number, y: number): number { return x + y; }; let myAdd = function(x: number, y: number): number { return x + y; };
  
-// The parameters 'x' and 'y' have the type numbe+// The parameters 'x' and 'y' have the type number
 let myAdd: (baseValue: number, increment: number) => number = let myAdd: (baseValue: number, increment: number) => number =
     function(x, y) { return x + y; };     function(x, y) { return x + y; };
줄 265: 줄 265:
 </code> </code>
  
-''this: void''는 ''addClickListener''가 ''onclick''이 ''this'' 유형을 필요로하지 않는 함수가 될 것으로 예상 함을 의미합니다. 둘째, 다음과 같이 ''this''를 갖는 호출 코드에 주석을 달아라.+''this: void''는 ''addClickListener''가 ''onclick''이 ''this'' 유형을 필요로하지 않는 함수가 될 것으로 예상 함을 의미합니다. 둘째, ''this''를 갖는 호출 코드에 주석을 달아라
 + 
 +<code javascript> 
 +class Handler { 
 +  info: string; 
 +  onClickBad(this: Handler, e: Event) { 
 +    // oops, used `this` here. using this callback would crash at runtime 
 +    this.info = e.message; 
 +  } 
 +
 +let h = new Handler(); 
 +uiElement.addClickListener(h.onClickBad); // error! 
 +</code> 
 + 
 +''this'' 주석을 사용하면 처리기의 인스턴스에서 onClickBad를 호출해야한다는 사실을 명시하게됩니다. 그런 다음 TypeScript는 addClickListener에 this: void가 있는 함수가 필요하다는 것을 감지합니다. 오류를 수정하려면 다음 유형을 변경하십시오. 
 + 
 +<code javascript> 
 +class Handler { 
 +  info: string; 
 +  onClickGood(this: void, e: Event) { 
 +    // can't use `this` here because it's of type void! 
 +    console.log('clicked!'); 
 +  } 
 +
 +let h = new Handler(); 
 +uiElement.addClickListener(h.onClickGood); 
 +</code> 
 +onClickGood는이 유형을 this: void로 지정하기 때문에 addClickListener에 전달할 수 있습니다. 물론 이것은 this.info를 사용할 수 없다는 것을 의미합니다. 둘 다 원한다면 화살표 함수를 사용해야합니다. 
 +<code javascript> 
 +class Handler { 
 +    info: string; 
 +    onClickGood = (e: Event) => { this.info = e.message } 
 +
 +</code> 
 +이것은 화살표 함수가 this를 사용하기 때문에 작동합니다. 그래서 당신은 항상 이것을 기대하는 무언가에 전달할 수 있습니다 this: void. 단점은 처리기 유형의 객체 당 하나의 화살표 함수가 작성된다는 것입니다. 한편, 메소드는 한 번만 작성되어 Handler의 프로토 타입에 첨부됩니다. 핸들러 유형의 모든 객체간에 공유됩니다. 
 + 
 +===== Overloads ===== 
 +<code javascript> 
 +let suits = ["hearts", "spades", "clubs", "diamonds"]; 
 + 
 +function pickCard(x: {suit: string; card: number; }[]): number; 
 +function pickCard(x: number): {suit: string; card: number; }; 
 +function pickCard(x): any { 
 +    // Check to see if we're working with an object/array 
 +    // if so, they gave us the deck and we'll pick the card 
 +    if (typeof x == "object") { 
 +        let pickedCard = Math.floor(Math.random() * x.length); 
 +        return pickedCard; 
 +    } 
 +    // Otherwise just let them pick the card 
 +    else if (typeof x == "number") { 
 +        let pickedSuit = Math.floor(x / 13); 
 +        return { suit: suits[pickedSuit], card: x % 13 }; 
 +    } 
 +
 + 
 +let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }]; 
 +let pickedCard1 = myDeck[pickCard(myDeck)]; 
 +alert("card: " + pickedCard1.card + " of " + pickedCard1.suit); 
 + 
 +let pickedCard2 = pickCard(15); 
 +alert("card: " + pickedCard2.card + " of " + pickedCard2.suit); 
 +</code> 
 +컴파일러가 올바른 유형 검사를 선택하기 위해 기본 JavaScript와 비슷한 과정을 거칩니다. 오버로드 목록을보고 첫 번째 오버로드로 진행하여 제공된 매개 변수를 사용하여 함수를 호출합니다. 일치하는 것을 찾으면,이 과부하를 올바른 과부하로 선택합니다. 이러한 이유 때문에 가장 구체적인 상세에서 거의 구체적인 상세까지 오버로드 순서로하는 것이 일반적입니다. 
 + 
 +pickCard(x) 함수는 모든 객체가 오버로드리스트의 일부가 아니므로 객체를 취하는 오버로드와 숫자를 취하는 오버로드의 두 가지 오버로드 만 있습니다. 다른 매개 변수 유형으로 pickCard를 호출하면 오류가 발생합니다. 
 + 
 +==== 예제 ==== 
 +<code javascript> 
 +function add(a: string, b: string): string; 
 +function add(a: number, b: number): string; 
 +function add(a, b): any { 
 +  return a + b; 
 +
 +</code> 
 + 
 +함수명과 매개변수의 개수는 같지만 타입을 다른 경우. 
 +다른 언어의 오버로드는 함수명만 동일하면 되지만 TypeScript의 오버로딩은 함수명과 매개변수의 갯수가 같아야 한다.
typescript/function.1564243613.txt.gz · 마지막으로 수정됨: 2025/04/15 10:05 (바깥 편집)