Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- AWS
- animation
- docker
- Generic
- Swift
- docker-compose
- Filter
- Interface
- ReactNative
- list
- LiveData
- union
- map
- ConstraintLayout
- elementAt
- react native
- recyclerview
- enum
- CLASS
- Foreign Key
- vuex
- Service
- function
- lifecycle
- MINUS
- class component
- Kotlin
- collection
- 생명주기
- mongoose
Archives
- Today
- Total
개발 일기
Function ? 본문
Typescript에서는 다음과 같이 함수를 정의할수가 있습니다.
function add(x: number, y: number): number {
return x + y;
}
let myAdd = function(x: number, y: number): number {
return x + y;
};
함수의 반환 부분을 보고 많은 부분을 파악할수 있어서 다음과 같은 내용을 생략을 할수도 있습니다.
let myAdd: (baseValue: number, increment: number) => number = function(
x: number,
y: number
): number {
return x + y;
};
Typescript에서는 Javascript에서와는 다르게 함수에서 제공하는 매개 변수와 실제로 호출할 때 매개 변수가 같아야합니다.
function buildName(firstName: string, lastName: string) {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // error, too few parameters
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
만약에 js와 같이 표시를 하지 않고 호출이 하고 싶은 경우에는 다음과 같이 작성이 가능합니다.
function buildName(firstName: string, lastName?: string) {
if (lastName) return firstName + " " + lastName;
else return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
혹은 기본값을 설정을 할수가 있습니다.
function buildName(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined); // still works, also returns "Bob Smith"
let result3 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result4 = buildName("Bob", "Adams"); // ah, just right
함수에서 n개의 매개변수를 받고 싶을 때 다음과 같이 사용이 가능합니다.
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
// employeeName will be "Joseph Samuel Lucas MacKinzie"
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
다음과 같은 내용에서는 에러가 발생합니다.
let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
createCardPicker: function() {
return function() {
let pickedCard = Math.floor(Math.random() * 52);
let pickedSuit = Math.floor(pickedCard / 13);
return { suit: this.suits[pickedSuit], card: pickedCard % 13 };
};
}
};
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
그 이유가 바로 this에 해당 되는 내용 때문에 그렇습니다.
그래서 저기에서는 this가 createCardPicker에 설정되기 때문입니다.
Arrow function 을 통해서 다음과 같이 해결할수도 있지만 그렇게 하면 타입이 any로 변경이 됩니다.
Typescript에서는 any을 최대한 사용을 안하는게 좋습니다.
그래서 최종적으로는 다음과 같이 할수가 있습니다.
Arrow function
let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
createCardPicker: function() {
// NOTE: the line below is now an arrow function, allowing us to capture 'this' right here
return () => {
let pickedCard = Math.floor(Math.random() * 52);
let pickedSuit = Math.floor(pickedCard / 13);
return { suit: this.suits[pickedSuit], card: pickedCard % 13 };
};
}
};
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
interface Card {
suit: string;
card: number;
}
interface Deck {
suits: string[];
cards: number[];
createCardPicker(this: Deck): () => Card;
}
let deck: Deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
// NOTE: The function now explicitly specifies that its callee must be of type Deck
createCardPicker: function(this: Deck) {
return () => {
let pickedCard = Math.floor(Math.random() * 52);
let pickedSuit = Math.floor(pickedCard / 13);
return { suit: this.suits[pickedSuit], card: pickedCard % 13 };
};
}
};
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
Typescript에서는 똑같은 함수의 이름으로 매개변수에 대한 정보만 틀리게 작성을 하고 싶은 경우에는 다음과 같이 작성이 가능합니다.
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);
'컴퓨터 언어 > Typescript' 카테고리의 다른 글
Unions and Intersection Types ? (0) | 2020.05.10 |
---|---|
Literal Types ? (0) | 2020.05.03 |
Class ? (0) | 2020.05.01 |
Interface ? (0) | 2020.04.30 |
변수 선언 ? (0) | 2020.04.26 |
Comments