TypeScript, this 라는 타입에 관하여

타입스크립트에서는 클래스에서 사용되는 this라는 타입이 있습니다. 이 this 타입은 동적으로 현재 클래스에 대한 타입으로 결정됩니다. 애매하고 어렵죠? 예시를 통해 좀더 살펴보면..

class Box {
  content: string = "";
  sameAs(other: this) {
    return other.content === this.content;
  }
}
 
class DerivedBox1 extends Box {
  otherContent: string = "?";
}

class DerivedBox2 extends Box {
  otherContent: string = "?";
}
 
const base = new Box();
const derived1 = new DerivedBox1();
derived1.sameAs(base);

const derived2 = new DerivedBox2();
derived2.sameAs(base);

위의 코드에서 Box 클래스의 sameAs 인자의 other 타입이 this입니다. 이 Box 클래스를 상속받는 파생클래스들을 통해 sameAs를 사용할 경우 sameAs의 첫번째 인자인 other는 각 파생클래스의 타입이 됩니다. 즉 derived1sameAs 매서드의 정의는 다음과 같고…

sameAs(other: DerivedBox1): boolean

derived2sameAs 매서드의 정의는 다음과 같습니다.

sameAs(other: DerivedBox2): boolean

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다