Front-end/TypeScript

[TypeScript] 함수

hyebin Lee 2022. 3. 6. 17:46

함수 타입 정의

//함수

function add(num1: number, num2: number): void {
  //return num1+num2
  console.log(num1 + num2);
}

function isAdult(age: number): boolean {
  return age > 19;
}

function hello(name?: string) {
  //name은 있어도 되고 없어도 되는 옵션 파라미터, 선택적 매개변수 이다.
  //옵션이어도 타입은 지켜줘야한다.
  return `Hello, ${name || "world"}`;
}

function hello2(name = "world") {
  //위 함수와 동일
  //default값을 줄 수 있다.
  return `Hello, ${name}`;
}

const result1 = hello();
const result2 = hello("Same");
//const result3 = hello(1);
function hello(name: string, age?: number): string {
  if (age !== undefined) {
    return `Hello ${name}. You are ${age}.`;
  } else {
    return `Hello ${name}.`;
  }
}

function hello2(age: number | undefined, name: string): string {
  if (age !== undefined) {
    return `Hello ${name}. You are ${age}.`;
  } else {
    return `Hello ${name}.`;
  }
}

console.log(hello("smae", 30));
console.log(hello2(30, "same"));
console.log(hello2(undefined, "same"));

여기서 주의 할 점은 옵션 파라미터가 name 앞에 오면 안된다.

즉, 선택적 매개변수가 필수 매개변수 앞에 오면 에러가 발생한다.

만약 age를 앞에 두고 옵션을 사용하고 싶다면 hello2와 같은 방법으로 사용한다. (명시적으로 undefinde를 전달하는 방식)

나머지 매개변수의 타입 측정

나머지 매개변수란? 매개변수의 갯수가 매번 바뀔 수 있다. 점세개는 전달받은 매개변수를 배열로 사용할 수 있게 한다.

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 {
  //User라는 인터페이스
  name: string; //name 속성
}
const Sam: User = { name: "Sam" }; //Sam이라는 객체, User타입

function showName(this: User) {
  //showName 함수,
  //this의 타입을 정해줘야함, 함수의 첫번째 매개변수 자리에 this를 쓰고 타입을 입력
  console.log(this.name); //this.name을 보여줌
}

//매개변수가 있을 때, 전달 매개변수는 this를 제외하고 시작
function showName2(this: User,age: number, gender: "m" | "f") {
  console.log(this.name, age, gender);
}

const a = showName.bind(Sam); //bind를 이용해서 this를 Same 객체로 강제
a();

오버로딩 함수

이 코드에서는 문제가 없어보이지만 실제 사용하면 에러가 뜬다.

sme 이 User객체를 반환하는데 확신이 없기 때문이다.

 

전달받은 매개변수의 타입에 따라 리턴되는 결과값이 다른데, 이럴때는 오버로드를 사용한다.

오버로드는 함수위에 똑같은 모습으로 작성을 하면 된다.

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

function join(name: string, age: number): User; //age가 숫자면 User를 반환
function join(name: string, age: string): 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("Sma", "30");