선택적 매개변수, 여러 개 파라미터, 오버로딩

旅人·2023년 3월 15일
0
// name은 optional 파라미터
function hello(name?: string): string {
  return `Hello, ${name || "world!"}`;
}

// 디폴트 파라미터
function hello2(name = "Sam"): string {
  return `Hello, ${name}`;
}

console.log(hello("Jack")); // Hello, Jack
console.log(hello("")); // Hello, world!
console.log(hello()); // Hello, world!
console.log(hello(undefined)); //Hello, world!

console.log(hello2()); // Hello, Sam

선택적 파라미터는 일반 파라미터 앞에 올 수 없다.

// optional parameter는 일반 parameter 앞에 올 수 없다.
function hi(name: string, age?: number): string {
  if (age != undefined) {
    return `Hello, ${name}. You are ${age}`;
  } else {
    return `Hello, ${name}`;
  }
}
console.log(hi("Sam")); // Hello, Sam
console.log(hi("Jack", 28)); // Hello, Jack. You are 28

// ------------------------------------

// 파리미터를 배열로 나타낼 수 있음
function add(...nums: number[]): number {
  return nums.reduce((result, num) => result + num, 0);
}
console.log(add(1, 2, 3)); // 6
console.log(add(1, 3, 5, 7, 9)); // 25

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"); // Sam 30 m

오버로딩을 통해 리턴 타입을 여러 개 가져갈 수 있다.

interface User {
  name: string;
  age: number;
}

/*

파라미터 타입에 따라 분기 처리 되어 리턴 타입이 변경될 때
여러가지 타입이 반환될수 있어 에러
--> 그럴 때는 함수 overload
*/

function join(name: string, age: number): User;

function join(name: string, age: string): string;

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", "95");

console.log(sam); // { name: 'Sam', age: 30 }
console.log(jane); // 나이는 숫자로 입력해주세요
profile
一期一会

0개의 댓글