C.W.K.
Stream
Lesson 04 of 05 · published

`this` Typing: Parameter 아닌 Parameter

~9 min · functions, this, this-parameter, noImplicitThis

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"`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` 의존하면 안 됨
}
`this` parameter 가 type system 과 JavaScript 의 dynamic `this` 사이의 다리. 함수가 타입 붙이고 싶은 특정 `this` 로 호출될 때, 또는 `this` 접근 완전히 금지하고 싶을 때 써.

Method-this 는 암묵적

일반 method (method 단축형으로 선언) 안에서 `this` 는 자동으로 둘러싼 object 의 타입. Parameter 필요 없어 — TypeScript 가 채움. 명시적 parameter 는 standalone 함수, callback, 또는 특정 `this` 로 호출돼야 할 call signature 있는 interface 에 타입 붙일 때만 필요.

피파의 고백

`this` parameter 거의 손으로 안 써. Method 가 무료로 줘. Arrow 함수는 필요 없어. 손 뻗는 case 는 더 옛 callback-shaped API 와의 통합 — 문서가 "row element 로 `this` 설정해서 호출" 같은 거 말하는 곳. 거기서 parameter 가 무가치 — host 환경이 약속한 거 정확히 type system 한테 말해.

Code

`this` parameter — 타입 전용·typescript
// `this` parameter — type-system 전용.

function printName(this: { name: string }) {
  return this.name;
}

// Match 되는 object 에 호출.
const me = { name: 'Pippa', printName };
me.printName();                                  // ✅ this 가 me

const loose: { printName: () => string } = { printName };  // ❌ printName 이 this: { name: string } 필요

// Runtime 에 함수가 0 args 받음 — `this` 안 셈.
printName.length;  // 0
`this: void` — `this` 안 필요한 callback·typescript
// `this: void` — `this` 접근 명시적으로 금지.

type PureCallback = (this: void, x: number) => string;

const pure: PureCallback = function (x) {
  // this;          // ❌ 여기서 `this` 는 void — 못 씀
  return `x=${x}`;
};

function useCallback(cb: PureCallback) {
  return cb(42);
}

// Arrow 함수가 자연스럽게 `this: void` 만족 — 밖에서 캡처하고
// closure 패턴이 runtime `this` 안 요구.
useCallback((x) => `x=${x}`);   // ✅

External links

Exercise

function highlight(this: HTMLElement) 써, this 에 class toggle. 그다음 event listener 로 붙여: el.addEventListener('click', highlight). Listener 가 this 를 element 로 받아? 그다음 plain 함수로 호출 시도: highlight(). TypeScript 가 어떤 에러 줘?
Hint
DOM event listener 가 default 로 this 를 element 로 설정. this parameter 와 함께, TypeScript 가 addEventListener 가 HTMLElement 에 호출되는지 검증 가능. highlight() 직접 호출은 검증할 this 없어서 실패.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고
💛 by 똘이warm

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.