[TypeScript Class]

Typescript Class(타입스크립트 클래스)

TS에서 Class를 생성하는 것은 JS에서와 큰 차이가 없다. 동일하게 Pascal Case로 Class 작명을 해준 후, Field를 작성하고, Constructor 키워드를 통해 생성자를 작성해주면 된다. 하지만 TS는 타입이 정의된 정적 타입 언어인만큼 Field와 Constructor의 arguments에도 타입을 정의해주어야 한다. 아래 코드로 JS와 TS로 각각 Class를 정의하는 방법을 확인해 보자.

//JavaScript
class Student {
  //field
  name;
  grade;
  age;
  //생성자
  constructor(name,grade,age){
    this.name = name;
    this.grade = grade;
    this.age = age;
  }
  study(){
    console.log("Study");
  }
}
const student = new Student("Tom","A+",10);

//TypeScript
class Student {
  //field
  name:string;
  grade:string;
  age:number;
  //생성자
  constructor(name:string,grade:string,age:number){
    this.name = name;
    this.grade = grade;
    this.age = age;
  }
  study(){
    console.log("Study");
  }
}
const student = new Student("Tom","A+",10);

FieldConstuctorarguments에 타입이 지정된 부분 말고는 차이점이 없는 것을 볼 수 있다.

또한 Class Inherit(클래스 상속)에 있어서도 큰 차이점이 없다. 마찬가지로 타입이 지정되는 부분에서만 차이점을 발견할 수 있다.

//Javascript
class Student {
  //field
  name;
  grade;
  age;
  //생성자
  constructor(name,grade,age){
    this.name = name;
    this.grade = grade;
    this.age = age;
  }
  study(){
    console.log("Study");
  }
  introduce(){
    console.log("hello!")
  }
}

//inherit
class StudentDev extends Student {
  //field
  favorite;
  //생성자
  constructor(name,grade,age,favorite){
    super(name,grade,age)
    this.favorite = favorite;
  }
  programming(){
    console.log(`${this.favorite}`)
  }
}
const student1 = new StudentDev("Bob","B",20,"Typescript");
//Typescript
class Employee {
  //field
  name:string;
  age:number;
  position:string;
  //생성자
  constructor(name:string, age:number,position:string){
    this.name = name;
    this.age = age;
    this.position = position;
  }
  work(){
    console.log("Work")
  }
}

class ExecutiveOfficer extends Employee {
  //field
  roomNum : number
  //생성자
  constructor(name:string,age:number,position:string,roomNum: number){
    super(name,age,position)
    this.roomNum = roomNum;
  }
}
const employeeA = new Employee("TOM",20,"dev");

JS에서 상속받는 것과 동일하게 Extends 키워드를 통해 Class를 상속 받고, 상속 받은 Class의 생성자 내부에서는 Super 키워드를 통해 상속받은 property들을 작성해주면 된다.

[Access Modifier(접근 제어자)]

Access Modifier(접근 제어자)

- Class의 Field에 접근에 대한 제어를 하는 역할의 키워드로 private, public, protected 3종류가 있다.

Public
- 따로 부여하지 않아도 기본값으로 설정되는 키워드로 Class의 내부, Class의 외부 모두에서 property에 접근을 할 수 있게 해준다.
Private
- 해당 Class 내부의 method에서만 본 키워드가 부여된 property에 접근이 가능하고 그 이외에는 어느 곳에서도 접근과 사용이 불가능하다.
Protected
- 해당 Class 내부와 상속받는 파생 Class에서만 접근이 가능하고 그 이외의 외부에서는 해당 property에 접근이 불가능하다.
class Employee {
  //field
  private name:string;
  protected age:number;
  public position:string;
  //생성자
  constructor(name:string, age:number,position:string){
    this.name = name;
    this.age = age;
    this.position = position;
  }
  work(){
    console.log(`${this.name}`)
  }
}
class ExecutiveOfficer extends Employee {
  //field
  roomNum : number
  //생성자
  constructor(name:string,age:number,position:string,roomNum: number){
    super(name,age,position)
    this.roomNum = roomNum;
  }
  func(){
    this.name; // Error
    this.age;
    this.position;
  }
}
const employeeA = new Employee("TOM",20,"dev");
employeeA.name = "Bob"; //Error
employeeA.age = 10;  //Error
employeeA.position = "V";

위의 코드에서 보면 name property private, age propertyprotected, position property public 제어자가 붙었다. 추가로 ExecutiveOfficer이라는 Employee의 파생 Class도 존재한다.

1. name property는 private이기 때문에 Employee Class 내부의 work method에서만 접근이 가능하고 파생 Class에서는 접근 시 오류가 발생하는 것을 볼 수 있다.
2. age property는 protected이기 때문에 파생 Class에서는 접근이 가능하다. 하지만 Class의 외부에서는 접근 시 오류가 발생하는 것을 볼 수 있다.
3. position property는 publice이기 때문에 특정 영역에 국한되지 않고 모든 곳에서 접근이 가능한 것을 볼 수 있다.

 

Access Modifier을 사용하는 방법에는 위와 같이 Field 값에 직접 부여하는 방법도 있지만 생성자에 직접 부여하는 방법도 존재한다. 이러한 경우 생성자가 자체적으로 Field를 만들기 때문에 Field에는 따로 제어자와 값을 정의하지 않아도 된다. 따라서 생성자에 제어자를 부여하는 경우 Field를 비워주어야 한다.

그에 더해 Field 값의 초기화까지 자동적으로 해주기 때문에 아래 코드와 같이 매우 간단한 코드로 작성이 가능하다.

class Employee {
  constructor(private name:string, protected age:number, public position:string){}
  work(){
    console.log("Work")
  }
}
접근 제어자는 객체 지향 프로그래밍에서 은닉화하는 경우에 굉장히 자주 사용된다.

[Interface & Class]

Interface & Class

InterfaceClass를 같이 사용하는 경우에는 InterfaceClass설계도, 청사진의 역할을 하게 된다. 따라서 Class를 생성할 때 Interface를 상속받는 느낌으로 코드를 구현하면 되는데 이 때 사용되는 키워드가 있다. 바로 Implements라는 키워드를 사용해서 Interface를 갖고 Class를 구현하게 되는데 Class를 상속받을 때 Extends 키워드를 통해 확장하여 상속을 받았듯이 Implements 키워드를 통해 Interface에 정의된 형태에 맞춰서 Class를 생성한다.

interface Character {
  name:string,
  speed: number,
  move():void
}

class CharacterA implements Character {
  name: string;
  speed: number;
  constructor(name:string,speed:number){
    this.name = name;
    this.speed = speed;
  }
  move():void {
    console.log("Move")
  }
}

여기서 주의해야할 점은 Interface를 통해서 생성되는 Field 값들은 무조건 Public 제어자를 갖게 된다. 따라서 Public이 아닌 다른 제어자를 사용하기 위해서는 Class의 Field나 생성자를 통해서 제어자를 별도로 부여해주어야 정상적으로 사용이 가능하다.

Interface와 Class는 자주 사용하게 되진 않지만 라이브러리의 구현이나 복잡하고 정교한 코드를 작성하는 경우에 유용하게 사용된다.

'Typescript' 카테고리의 다른 글

[TypeScript] - (8) Type 조작  (0) 2024.08.14
[TypeScript] - (7) Generic(제네릭)  (2) 2024.08.07
[Typescript] - (5) Interface  (0) 2024.08.01
[Typescript] - (4) Typescript 함수  (0) 2024.07.31
[Typescript] - (3) Typescript 이해하기  (0) 2024.07.26

+ Recent posts