📘 TypeScript

TypeScript - 함수의 명시적 this 타입

zunwon 2023. 11. 21. 15:25

함수의 명시적 this 타입

interface User {
  name: string;
}
function greet(msg: string) {
  return `Hello ${this.name}, ${msg}`;
}

const baek = {
  name: "Baek",
  greet,
};
baek.greet("Good morning~"); // Hello Baek, Good morning~

const neo = {
  name: "Neo",
};
greet.call(neo, "Good afternoon~"); // Hello Neo, Good afternoon~
  • this에서 타입이 선언되어 있지 않기 때문에 암시적으로 any타입으로 지정된다
  • this가 최소한 "User interface의 구조는 가지고 있어야 한다"를 선언해야 한다
function greet(this: User, msg: string) {
  return `Hello ${this.name}, ${msg}`;
}
  • 위의 코드와 같이 greet() 함수를 바꿔면 에러가 발생하지 않는다
  • 따라서 함수 매개변수 안에서 this라는 이름으로 정의할 수 있다