C.W.K.
Stream
Lesson 01 of 06 · published

Class 문법: 멤버, Constructor, Method

~9 min · classes, syntax, members

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"TypeScript class 는 타입 체크 있는 JavaScript class. 같은 문법, 더 많은 보장."

기본 모양

TypeScript class 선언이 필드, parameter, return 타입에 타입 annotation 있는 JavaScript class 문법. Class 필드가 이름과 타입으로 선언; constructor 가 초기화; method 가 필드 읽고 수정; class instance 모양이 이 모든 거 type system 통해 carry.

class Counter {
  count: number = 0;
  increment(): void { this.count++ }
  reset(): void { this.count = 0 }
}

`count: number = 0` 가 필드 선언 + 초기화. Method 가 `this.count` 접근 — TypeScript 가 method 안 `this` 는 Counter 라는 거 아니까 타입 보존.

Class instance 타입

Class 선언이 constructor (값 `Counter`) 와 타입 (타입 `Counter`) 둘 다 만들어. const c: Counter = new Counter() 가 타입 사용; new Counter() 가 constructor 호출. 둘이 같은 이름 공유, 대부분 TypeScript 코드가 자유롭게 섞어.

Getter 와 setter

Class method 가 `get` 과 `set` keyword 써서 property-like accessor 만들 수. get name(): string 가 getter 선언; `instance.name` 읽으면 호출. set name(v: string) 가 setter 선언; `instance.name = '...'` assign 하면 호출. Class 밖에선 accessor 가 property 처럼 보임; 안에선 두 method.

Class 가 행동 + state 가 여러 instance 와 결합될 때 가장 잘 작동. 순수 값 모양엔 interface 써. 일회성 object 엔 object literal 써. Class 는 많은 instance 에 데이터와 method 둘 다 필요할 때 빛나.

Code

Class 기본 — 필드, constructor, method, accessor·typescript
class User {
  name: string;
  email: string;
  active: boolean = true;

  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }

  greet(): string {
    return `Hi, ${this.name}`;
  }

  // Getter
  get isActive(): boolean {
    return this.active;
  }

  // Setter
  set isActive(v: boolean) {
    this.active = v;
    console.log(`active changed to ${v}`);
  }
}

const u = new User('Pippa', 'pippa@example.com');
u.greet();              // 'Hi, Pippa'
u.isActive;             // true (getter 통해)
u.isActive = false;     // setter 가 'active changed to false' 로깅

External links

Exercise

start(), stop(), reset() method 와 get elapsed(): number accessor 가진 Stopwatch class 써. 내부적으로 시작 시간 추적. Type system 이 method 체인 통해 class instance 타입 추적 확인.
Hint
필드 private _start: number | null = null. Method 가 _start set/read. Getter 가 started 면 Date.now() - this._start 계산, 아니면 0.

Progress

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

댓글 0

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

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