본문 바로가기
프론트엔드/TypeScript

클래스

by alswlfl 2023. 1. 3.

클래스

  • 타입스크립트에서는 멤버 변수는 미리 선언해주어야 함
class Car{
  color:string;  //타입스크립트에서는 멤버변수는 미리 선언해주어야 함
  constructor(color:string){
    this.color=color;
  }
  start(){
    console.log("start");
  }
}

const bnw=new Car("red");
  • 멤버 변수 미리 선언하지 않는 방법 -> 접근 제한자 또는 readonly키워드 이용
class Car2{
  constructor(public color:string){
    this.color=color;
  }
  start(){
    console.log("start");
  }
}

class Car3{
  constructor(readonly color:string){
    this.color=color;
  }
  start(){
    console.log("start");
  }
}

접근 제한자(Access modifier) - public, private, protected

  • 타입스크립트에서는 접근 제한자 지원
  • public: 자식클래스나 클래스 인스턴스에서 모두 접근 가능(아무것도 표시 안하면 public임)
  • private: 자식클래스에서 사용 불가능, 해당 클래스 내에서만 사용 가능 (#으로 표기하면 privated임)
  • protected: 자식 클래스에서 접근 가능하지만, 클래스 인스턴스로는 참조 불가능
class Car4{
  name: string="car";
  color: string;
  constructor(color: string){
    this.color=color;
  }
  start(){
    console.log("start");
  }
}

class Bmx extends Car4{
  constructor(color:string){
    super(color);
  }
  showName(){
    console.log(super.name);
  }
}

readonly 키워드

  • 해당 변수 수정 불가능
  • 수정 가능하게 하려면 constructor내부에서 해당 작업을 가능하게 해주면 됨
  • static사용하면, 정적 멤버 변수를 만들 수 있음 -> this가 아닌 클래스 명을 적어줌
class Car5{
  readonly name:string="car";
  color: string;
  static wheels=4;
  constructor(color: string, name){
    this.color=color;
    this.name=name;
  }
  start(){
    console.log("start");
    console.log(Car5.wheels);
  }
}
class Bmx2 extends Car5{
  constructor(color:string, name){
    super(color, name);
  }
  showName(){
    console.log(super.name);
    console.log(Car5.wheels);
  }
}

추상 클래스(abstract)

  • property나 메서드의 이름만 선언해주고, 구체적인 기능은 상속방는 쪽에서 구현
  • 추상 클래스는 new이용하여 객체 만들 수 없음 -> 상속을 통해서만 사용 가능
  • 추상 클래스 내부의 추상 메서드는 반드시 상속받은 쪽에서 구체적인 구현을 해주어야 함
abstract class Car6{
  color: string;
  constructor(color: string){
    this.color=color;
  }
  start(){
    console.log("start");
  }
  abstract doSomething():void;
}
class Bmw6 extends Car6{
  constructor(color: string){
    super(color);
  }
  doSomething(){
    alert(3);
  }
}

'프론트엔드 > TypeScript' 카테고리의 다른 글

제네릭  (0) 2023.01.03
리터럴, 유니온/교차 타입  (0) 2023.01.03
함수  (0) 2023.01.03
인터페이스  (0) 2023.01.03
TypeScript 사용 이유와 기본 타입  (0) 2023.01.03