"`this` 는 모든 method 가 가진 비밀 첫 parameter. TypeScript 가 그걸 명시하게 해줘."
`this` parameter
TypeScript 가 특별한 parameter 문법 가짐: this 라 이름 붙은 첫 parameter 예약. Runtime parameter 아냐 — 호출할 때 명시적으로 전달 안 함. 대신 type system 한테 함수 안 `this` 가 뭐여야 하는지 말함.
function sayName(this: { name: string }) {
return this.name;
}
이 `this` annotation 은 compile 시점에 erase. Runtime 에 함수가 0개 argument 받음. 근데 type system 이 이걸 써서 `sayName` 이 `name` property 가진 object 에만 호출되는지 체크.
왜 이 parameter 중요
`noImplicitThis` (strict-mode flag) 없으면, 함수 안 annotation 없는 `this` 가 default 로 `any` — 즉 모든 `this.foo` 접근이 조용히 통과. Strict mode 켜진 상태에선 annotation 없는 `this` 가 많은 문맥에서 에러. `this` parameter 가 원칙 있는 fix: compiler 한테 `this` 가 정확히 어떤 모양이어야 하는지 말해.
가장 흔한 use case 는 re-bind 되는 callback. jQuery 같은 library API (그리고 많은 DOM API) 가 너의 callback 을 특정 `this` 로 호출. Parameter 없으면 안에서 `this.something` 안전하게 접근 못 함.
void marker
this: void 는 "이 함수가 `this` 안 씀" 말함. Callback 이 context-free 여야 한다고 선언하는 방법 — 여러 방식으로 전달될 수 있는 callback 받을 때 유용.
function safeCallback(fn: (this: void, x: number) => void) {
fn(42); // fn 이 `this` 의존하면 안 됨
}
Method-this 는 암묵적
일반 method (method 단축형으로 선언) 안에서 `this` 는 자동으로 둘러싼 object 의 타입. Parameter 필요 없어 — TypeScript 가 채움. 명시적 parameter 는 standalone 함수, callback, 또는 특정 `this` 로 호출돼야 할 call signature 있는 interface 에 타입 붙일 때만 필요.