FRONTMANFRONTMAN
  • 태그
  • 방명록
  • 글쓰기
  • 관리자
  • HOME
  • 태그
  • 방명록
TypeScript에서의 클래스
hahekaku
TypeScript에서의 클래스Language/TypeScript2023. 10. 18. 14:14@hahekaku
Table of Contents

TypeScript는 객체 지향 프로그래밍(OOP, object-oriented programming) 스타일을 지원하며, 클래스(class)를 사용하여 코드의 구조를 더욱 체계적으로 작성할 수 있도록 돕습니다. 이 글에서는 TypeScript에서 클래스 정의와 생성자 타입, 접근 제어자(public, private, protected), 읽기 전용 속성(readonly), 추상 클래스(abstract class)와 인터페이스 구현에 대해 자세히 알아보겠습니다.

클래스 정의 및 생성자

클래스는 객체를 생성하기 위한 템플릿입니다. TypeScript에서 클래스는 다음과 같이 정의할 수 있습니다.

class User {
  username: string;
  age: number;

  constructor(username: string, age: number) {
    this.username = username;
    this.age = age;
  }

  greet() {
    console.log(`안녕하세요, 저는 ${this.username}입니다.`);
  }
}

const user1 = new User('홍길동', 25);
user1.greet(); // 안녕하세요, 저는 홍길동입니다.

생성자 타입 정의

생성자(constructor)는 클래스의 인스턴스를 초기화합니다. 생성자에서 사용할 매개변수는 타입을 명시할 수 있으며, 이를 통해 강력한 타입 검사를 받을 수 있습니다.

class Product {
  name: string;
  price: number;

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

const product1 = new Product('냉장고', 500000);
console.log(product1.name); // 냉장고

접근 제어자: public, private, protected

TypeScript는 접근 제어자를 사용하여 클래스 멤버(속성 및 메서드)의 접근 범위를 설정할 수 있습니다.

public

public은 기본 접근 제어자입니다. 클래스 외부에서도 접근할 수 있습니다.

class PublicExample {
  public name: string;

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

const example = new PublicExample('테스트');
console.log(example.name); // 테스트

private

private로 선언된 멤버는 클래스 내부에서만 접근할 수 있습니다.

class PrivateExample {
  private secret: string;

  constructor(secret: string) {
    this.secret = secret;
  }

  getSecret(): string {
    return this.secret;
  }
}

const example = new PrivateExample('비밀');
console.log(example.getSecret()); // 비밀
// console.log(example.secret); // 오류: 'secret'은 private입니다.

protected

protected는 private와 비슷하지만, 상속받은 클래스에서도 접근할 수 있습니다.

class Parent {
  protected message: string;

  constructor(message: string) {
    this.message = message;
  }
}

class Child extends Parent {
  showMessage() {
    console.log(this.message);
  }
}

const child = new Child('안녕하세요');
child.showMessage(); // 안녕하세요

읽기 전용 속성: readonly

readonly는 클래스의 속성이 한 번만 설정되도록 강제합니다. 주로 초기화 과정에서 값을 할당하고 변경하지 않을 경우 사용합니다.

class Book {
  readonly title: string;

  constructor(title: string) {
    this.title = title;
  }

  getTitle() {
    return this.title;
  }
}

const book = new Book('타입스크립트 완벽 가이드');
console.log(book.title); // 타입스크립트 완벽 가이드
// book.title = '새로운 제목'; // 오류: 'title'은 readonly입니다.

추상 클래스와 인터페이스 구현

추상 클래스는 공통 동작과 속성을 정의하고, 이를 상속받는 클래스에서 구현하도록 강제하는 데 사용됩니다. 인터페이스는 클래스가 따라야 하는 계약을 정의합니다.

추상 클래스

추상 클래스는 직접 인스턴스화할 수 없으며, 반드시 상속받아야 합니다.

abstract class Vehicle {
  abstract move(): void;

  startEngine() {
    console.log('엔진을 시작합니다.');
  }
}

class Car extends Vehicle {
  move() {
    console.log('차가 움직입니다.');
  }
}

const car = new Car();
car.startEngine(); // 엔진을 시작합니다.
car.move(); // 차가 움직입니다.

인터페이스 구현

인터페이스는 클래스가 특정 속성과 메서드를 반드시 구현하도록 강제합니다.

interface Animal {
  name: string;
  makeSound(): void;
}

class Dog implements Animal {
  name: string;

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

  makeSound() {
    console.log('멍멍!');
  }
}

const dog = new Dog('뭉치');
dog.makeSound(); // 멍멍!

TypeScript의 클래스는 강력한 타입 시스템과 함께 객체 지향 프로그래밍의 유연성을 제공합니다. 위 내용을 참고하여 코드의 가독성과 유지보수성을 높일 수 있습니다.

 

'Language > TypeScript' 카테고리의 다른 글

TypeScript 모듈 (export, import)  (2) 2023.10.19
조건부 타입(Conditional Types)  (0) 2023.10.18
TypeScript 매핑 타입(Mapped Types)  (0) 2023.10.17
TypeScript keyof와 인덱스 타입  (0) 2023.10.17
TypeScript 타입 가드(Type Guards)  (0) 2023.10.17
Language/TypeScript 추천 글
more
  • TypeScript 모듈 (export, import)
    TypeScript 모듈 (export, import)2023.10.19
  • 조건부 타입(Conditional Types)
    조건부 타입(Conditional Types)2023.10.18
  • TypeScript 매핑 타입(Mapped Types)
    TypeScript 매핑 타입(Mapped Types)2023.10.17
  • TypeScript keyof와 인덱스 타입
    TypeScript keyof와 인덱스 타입2023.10.17
FRONTMAN

검색

250x250

방문자 수

Total
Today
Yesterday

카테고리

  • 분류 전체보기 (54)
    • Language (48)
      • JavaScript (15)
      • TypeScript (14)
      • Python (14)
      • Dart (5)
      • Java (0)
    • FE (6)
      • WEB (4)
      • React (0)
      • Flutter (1)
    • CS (0)
      • Algorithm (0)
      • Network (0)
    • DevOps (0)

공지사항

  • 전체보기

최근 글

인기 글

태그

  • typeScript
  • 타입
  • Flutter
  • Python
  • npm
  • OOP
  • 타입스크립트
  • function
  • CLASS
  • inline frame
  • Modules
  • 자바스크립트
  • Object
  • JavaScript
  • 웹
  • list
  • Interface
  • 파이썬
  • DART
  • export
  • nodejs
  • async
  • tuple
  • js
  • await
  • Type
  • Import
  • 리스트
  • web
  • frontend

최근 댓글

FRONTMAN :: hahekaku
CopyrightBluemivDesigned byBluemiv

티스토리툴바