사용자 도구

사이트 도구


typescript:function

차이

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

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
typescript:function [2019/07/28 04:52] – [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; };
줄 302: 줄 302:
  
 ===== Overloads ===== ===== 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.1564289561.txt.gz · 마지막으로 수정됨: 2025/04/15 10:05 (바깥 편집)