본문 바로가기
Frontend/Typescript

Typescript class 🏛

by 우보틀 2022. 4. 19.

es6에서는 class가 등장하였습니다.

class는 syntatic sugar로서 이를 babel로 변환하면 prototype으로 변환되는 것을 볼 수 있습니다.

syntatic sugar란 alias와 같은 개념으로 이해하시면 좋습니다. 복잡한 기능을 간단하게 사용할 수 있도록 도와줍니다.

React의 jsx도 대표적인 Syntatic sugar입니다.

 

Typescript에서 class를 사용하는 경우 어떠한 것들을 적용해야 하는지 알아보려 합니다.

 

js class

class Person {
  constructor(name){
    this.name = name
  }
  
  sayName() {
    console.log(this.name)
  }
}

 

 

ts class

typescript에서는 변수를 미리 선언해주어야 합니다.

또한 constructor에서 입력받는 인자에 type을 지정해주어야합니다.

class Person {
  // typescript에서의 클래스는 미리 변수를 선언해주어야 합니다.
  name: string
  
  constructor(name: string){
    this.name = name
  }
  
  sayName() {
    console.log(this.name)
  }
}

 


접근 제한자

앞서 ts의 class에서는 미리 변수를 선언해주어야 한다고 했습니다.

이때 접근 제한자를 사용할 수 있습니다

사용할 수 있는 접근 제한자에는 public, protected, private가 있습니다.

 

public은 모든 영역에서

protected는 자식 클래스와 자신의 내부에서만

private는 자신의 내부 에서만 접근이 가능합니다.

 

class Person {
  public name: string
  protected phone: string
  private money: number
  
  constructor(name: string, phone: string, money: number) {
    this.name = name;
    this.phone = phone;
    this.money = money;
  }
}

const logan = new Person('logan', '010', '10000')

logan.name // 🟢
logan.phone // 🔴
logan.money // 🔴

class Student extends Person {
  constructor(name: string, phone: string, money: number) {
    super(name, phone, money)
    
    console.log(this.name)  // 🟢
    console.log(this.phone) // 🟢
    console.log(this.money) // 🔴
  }
}

 


readonly 키워드

readonly 속성을 사용하여 재할당이 불가능하게 할 수 있습니다.

속성이 변하면 안되는 인스턴스에 readonly 키워드를 사용하여 불변을 보장해야할 수 도 있습니다.

class Person {
  private readonly MAX_HOUSE: number = 2

  constructor(name){
    this.name = name
  }
  
  sayName() {
    console.log(this.name)
  }
  
  sayHouse() {
    this.MAX_HOUSE = 20 // 🔴
    console.log(this.MAX_HOUSE)
  }
}

 

 


static 키워드

static 메서드를 선언하면 클래스의 이름으로 호출하여야 합니다.

생성된 인스턴스에서는 호출이 불가능 합니다.

class Person {
  constructor(name){
    this.name = name
  }
  
  static sayHi() {
    return 'hihi'
  }
  
  sayName() {
    console.log(this.name)
  }
}

console.log(Person.sayHi()) // hihi

const logan = new Person('logan')
console.log(logan.sayHi) // 🔴

 


추상 클래스

추상 클래스에는 아직 정의되지 않은 메서드와 정의되어진 메서드가 혼합될 수 있습니다.

다른 클래스에서 추상 클래스를 상속받았다면 추상 메서드는 무조건 정의되어야 합니다

abstract class Person {
  constructor(name){
    this.name = name
  }
  
  sayName() {
    console.log(this.name)
  }
  
  abstract sayHi(): void;
}


class Student extend Person {
  constructor(name: string) {
    super(name)
  }
  
  sayHi() {
    console.log('hihi')
  }
}

const logan = new Student('logan');
logan.sayName()
logan.sayHi()

 

아래와 같은 방식으로 추상클래스를 관리하면

상속받는 모든 클래스에서 필수로 추상 메서드가 정의되어야 하므로 관리하기가 쉬워졌던 경험이 있습니다.

 

export abstract class AbstractCommand {
  constructor() {}
  
  public abstract load(program: Command): void;
}





export class GenearateCommmand implements AbstractCommand {
  public load(program: Command): void {
    console.log('this is generate')
  }
}

export class SpecialCommmand implements AbstractCommand {
  public load(program: Command): void {
      console.log('this is special')
  }
}

 

 


 

출처: https://poiemaweb.com/typescript-class

 

TypeScript - Class | PoiemaWeb

ES6에서 새롭게 도입된 클래스는 기존 프로토타입 기반 객체지향 언어보다 클래스 기반 언어에 익숙한 개발자가 보다 빠르게 학습할 수 있는 단순명료한 새로운 문법을 제시하고 있다. 하지만

poiemaweb.com