본문 바로가기
카테고리 없음

Typescript #4 함수

by nh_3521099031483 2024. 5. 3.

타입스크립트 함수에 대해 알아보자.

// 함수가 반환하는 타입을 적어주면 된다
function add(num1:number, num2:number): number{
  return num1 + num2;
}
// 아무것도 리턴해주지 않으면 void라고 적어주면 된다
function add2(num1:number, num2:number): void{
  // return num1 + num2;
  console.log(num1+num2)
}
// 원하는 리턴 타입을 넣어준다
function isAdult(age: number): boolean {
  return age > 19;
}
// 인터페이스처럼 함수의 매개변수도 옵셔널(?)로 지정할 수 있다.
function hello(name: string) {
  return `Hello, ${name || "world"}`; // name이 없을때의 코드가 있지만
}

const result1 = hello(); // 이 상태에서 호출하면 에러가 발생한다. 하나의 매개변수가 필요하기 때문,

function hello2(name?: string) { // 옵셔널로 바꿈, 타입은 지켜줘야 한다.
  return `Hello, ${name || "world"}`; // name이 없을때의 코드가 있지만
}

const result2 = hello2(); // 옵셔널로 바꾸니 에러가 사라진다.

function hello3(name = 'world') { // 초기값을 넣어줘도 옵셔널로 처리된다. 위에 있는 것이랑 똑같다.
  return `Hello, ${name}`; 
}

function hello4(name:string, age?:number):string { // 나이는 입력을 해도 되고 안해도 된다.
if (age !== undefined) {
  return `Hello, ${name}. you are ${age}.`;
} else {
  return `Hello, ${name}`;
  }
}
// age를 앞에다가 쓰고 싶은 경우엔 이렇게 작성해야 한다.
function hello5(age:number | undefined, name:string):string { // 나이는 입력을 해도 되고 안해도 된다.
if (age !== undefined) {
  return `Hello, ${name}. you are ${age}.`;
} else {
  return `Hello, ${name}`;
  }
}
console.log(hello5(30, "Sam"));
console.log(hello5(undefined, "Sam"))

// 1. 나머지 매개변수의 타입 작성 방법 예제
function add3(...nums: number[]) {
  return nums.reduce((result, num) => result + num, 0);
}

add3(1, 2, 3); // 6
add3(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 55

// 2. this와 관련된 내용 예제
interface User {
  name: string;
}

const Sam: User = {name:'sam'}

function showName(){
  console.log(this.name) // this 타입이 결정되지 않아서 빨간 줄이 나옴
}

const a = showName.bind(Sam); // bind를 이용해서 this를 Sam객체로 강제하고 있다.
a() // 'Sam'

function showName2(this:User){ // this에 타입 설정
  console.log(this.name) // this 타입이 결정 됨.
}

function showName3(this:User, age:number, gender:"m"|"f"){ // this에 타입 설정
  console.log(this.name, age, gender) // this 타입이 결정 됨.
}

const a3 = showName3.bind(Sam); // bind를 이용해서 this를 Sam객체로 강제하고 있다.
a3(30, 'm') // 'Sam', 30, 'm'
// 3. 오버로드 예제
interface User {
  name: string;
  age: number;
}

function join(name:string, age: number | string): User | string { // age가 number일땐 User객체 타입 반환, string일땐 string타입 반환
  if(typeof age === "number") {
    return {
      name,
      age,
    };
  } else {
    return "나이는 숫자로 입력해주세요"
  }
}

const sam: User = join("Sam", 30); // sam이 User객체를 반환하는 데 확신이 없어서 에러가 난다.
// 이럴 땐 오버로드를 사용한다.
const jane: string = join("Jane", "30")
// 함수 오버로드는 전달 받은 매개변수의 갯수나 타입에 따라 다른 동작을 하게 하는 것을 의미한다.
function join2(name: string, age: string): string;
function join2(name: string, age: number): User; // 원래 함수 위에 똑같은 모습으로 작성해주면 된다.
function join2(name:string, age: number | string): User | string {
  if(typeof age === "number") {
    return {
      name,
      age,
    };
  } else {
    return "나이는 숫자로 입력해주세요.";
  }
}
// 동일한 함수지만 매개변수의 타입이나 개수에 따라 다른방식으로 동작해야 된다면 오버로드를 사용할 수 있다.
const sam2: User = join2("Sam", 30); 
const jane2: string = join2("Jane", "30");