함수 (명시적 this, 오버로드)

2022. 12. 26. 17:01프로그래밍/TypeScript

    목차

명시적 this

this의 타입을 명시적으로 선언 가능
첫 번째 가짜 매개변수로 선언함
interface Cat {
  name: string;
  age: number;
}

const cat: Cat = {
  name: 'Lucy',
  age: 3
};

function hello(this: Cat) {
  // call 메서드로 호출되어 this가 바인딩 됨
  // this: Cat = { name: 'Lucy', age: 3 };
  console.log(`Hello ${this.name}`);
}

// call 메서드: 
// 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 
// 호출한 함수의 this에 바인딩 함
hello.call(cat); // Hello Lucy

 

오버로드 (Overloads)

이름은 같지만 매개변수/반환 타입이 다른 함수를 정의하는 것
함수 선언부와 구현부의 매개변수 개수가 같아야 함
인터페이스/타입별칭 등 메소드 정의에서도 활용 가능
// 함수 선언
function add(a: string, b: string): string;
function add(a: number, b: number): number; 

// 함수 구현
function add(a, b) {
  return a + b;
}

add('hello ', 'world'); // 'hello world'
add(1, 2); // 3
add('hello ', 2) // Error. 일치하는 오버로드가 없음
// 인터페이스
interface User {
  name: string,
  age: number,
  getData(x: string): string[], // 오버로드
  getData(x: number): string // 오버로드
}

const user: User = {
  name: 'Neo',
  age: 36,
  getData: (data: any) => {
    // 타입 가드
    if (typeof data === 'string') {
      return data.split('');
    } else {
      return data.toString();
    }
  }
};

user.getData('Hello'); // ['h', 'e', 'l', 'l', 'o']
user.getData(123); // '123'