728x90
반응형
선택적 매개변수
function hello(name?:string){
return `Hello, ${name || "world"}`;
}
function hello2(name = "world"){
return `Hello, ${name}`;
}
const result = hello();
const result2 = hello("Sam");
const result3 = hello(123); // Error
name이 없으면 "world"를 출력하는 코드이다. name은 있어도 되고 없어도 되는 매개변수이므로 뒤에 물음표를 붙인다. 이를 선택적 매개변수라고 부른다. 자바스크립트에서처럼 매개변수의 디폴트 값을 지정하는 것도 가능하다.
function hello(age:number|undefined, name:string):string{
if(age != undefined){
return `Hello, ${name}. You are ${age}.`;
} else{
return `Hello, ${name}`;
}
}
console.log(hello(30, "Sam"));
console.log(hello(undefined, "Sam"));
선택적 매개변수가 필수 매개변수보다 앞에 오면 에러가 발생한다. 선택적 매개변수를 앞에 쓰고 싶다면 age 뒤에 물음표를 붙이는 방식이 아니라 number 또는 undefined를 가질 수 있도록 하고 명시적으로 undefined를 전달한다.
나머지 매개변수의 타입 작성법
function add(..nums:number[]){
return nums.reduce((result, num) => result + num, 0);
}
add(1, 2, 3); // 6
add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 55
나머지 매개변수는 전달받은 매개변수를 배열로 나타낼 수 있게 한다. 따라서 매개변수 타입은 배열 형태로 지정해준다.
this
interface User{
name:string;
}
const Sam:User = { name:'Sam' }
function showName(this:User, age:number, gender:'m'|'f'){
console.log(this.name, age, gender)
}
const a = showName.bind(Sam);
a(30, 'm');
this의 타입을 정할 때는 함수의 첫 번째 매개변수 자리에 this를 쓰고 타입을 입력해주면 된다. 전달한 매개변수는 this 다음부터 적용된다.
overload
interface User{
name: string;
age: number;
}
function join(name:string, age:string):string;
function join(name:string, age:number):User;
function join(name:string, age:number|string):User|string{
if(typeof age === "number"){
return {
name,
age,
};
} else{
return "나이는 숫자로 입력해주세요.";
}
}
const sam:User = join("Sam", 30);
const jane:string = join("Jane", "30");
age의 타입에 따라 함수의 리턴값이 달라진다.
함수 오버로드는 전달받은 매개변수의 개수나 타입에 따라 다른 동작을 하게 하는 것을 의미한다.
728x90
반응형
'Language > Typescript' 카테고리의 다른 글
[Typescript] 클래스(Class) (0) | 2022.02.20 |
---|---|
[Typescript] 리터럴, 유니온/교차 타입 (0) | 2022.02.19 |
[Typescript] 인터페이스(interface) (0) | 2022.02.17 |
[Typescript] 기본 타입 (0) | 2022.02.17 |
[Typescript] 타입스크립트를 쓰는 이유를 알아보자 (0) | 2022.02.16 |