[Typescript] 기초 다지기 3. 클래스

dee·2022년 10월 5일
3

typescript

목록 보기
3/5
post-thumbnail

기초 3. 클래스

자바스크립트에 없는 타입스크립트만 가지고 있는 클래스 문법이 있다.
접근 제어자라는 것인데 속성이나 메서드 앞에 정의하여 접근 가능한 경우를 설정할 수 있다.

접근 제어자(Access Modifiers)

  • public
    • 클래스 바디 내에서 속성 선언시 생략해도 public으로 인식한다.
    • 클래스 내부, 외부에서 모두 접근 가능하다.
  • protected
    • 속성을 가진 클래스와 서브 클래스 인스턴스에서만 접근 가능하다.
  • private
    • 속성을 가진 클래스 내부에서만 접근 가능하다.

예제를 통해서 어떻게 실행되는지 알아보자.
클래스 Bird 안에 name, age, wings가 각각 public, protected, private로 선언되어있다. 클래스 Parrot은 Bird를 상속받고 있으며 메서드를 통해 age와 wings의 값을 반환하려고 한다.
클래스 Parrot를 new 연산자와 함께 호출하여 새로운 parrot이라는 인스턴스를 생성하였다. 그리고 이 인스턴스를 통해 Bird 안에 선언한 속성에 접근하고자 한다.

class Bird {
	public name: string; // 앞의 public 생략 가능 (name: string)
	protected age: number;
	private wings: number;
    
    constructor(name: string, age: number, wings: number){
    	this.name = name;
      	this.age = age;
      	this.wings = wings;
    }

	getName(): string {
    	return this.name; // 접근 가능
    }
}

class Parrot extends Bird {
	getAge(): number {
    	return this.age;
    }
  
  	getWings(): number {
    	return this.wings; // Error: class 'Bird'안에서만 접근 가능.
    }
}

const parrot = new Parrot('Nabi', 12, 2);

console.log(parrot.name); // Nabi
console.log(parrot.age); // Error : class 'Bird' and its subclasses만 접근 가능.
console.log(parrot.wings); // Error : class 'Bird'안에서만 접근 가능.
console.log(parrot.getName()); // Nabi;
console.log(parrot.getAge()); // 12;
console.log(parrot.getWings()); 

결과를 살펴보면 아래와 같다.

접근 제어자속성결과
publicname   타입체커의 에러없이 접근
protected  age인스턴스의 속성으로는 접근 불가
인스턴스의 메서드 getAge로는 접근 가능
-> 클래스 Parrot 자체가 Bird의 서브 클래스이기 때문에 가능
privatewings    인스턴스 속성 및 메서드로 접근 불가
-> 클래스 Bird 내부에서만 접근 가능

🧐 접근 제어자에 따라 클래스의 속성과 메서드 활용 범위가 달라짐으로 정확히 인지하고 쓸 필요가 있다. 하지만 여기서 보여지는 에러들은 타입스크립트 컴파일 과정에서 출력해준다. 접근 제어자는 자바스크립트에 없는 것이기에 컴파일되고 나면 우리가 아는 일반 클래스의 속성과 메서드가 되어버린다!


constructor 매개변수에 접근 제어자와 함께 선언하기

constructor에서 접근 제어자 + 매개 변수 + 타입를 한 번에 선언할 수 있다. 이러면 따로 클래스 바디에 타입을 선언하지 않아도 자동으로 선언되며 construtor안에 속성들을 선언해준다.

// 작성한 코드
class Bird {
	constructor(public name: string, protected age: number, private wings: number){}
}
// declare
class Bird {
    name: string;
    protected age: number;
    private wings;
    constructor(name: string, age: number, wings: number);
}

수식어

접근 제어자와 같이 사용할 수 있다.

  • static
    * 수식어를 사용하면 클래스가 인스턴스를 생성하지 않고 속성과 메서드를 사용할 수 있다.

  • readonly
    * 속성에서만 사용 가능

    • 읽기만 가능하므로 다른 값을 할당할 수 없다.
class Bird {
	public readonly name: string;
	static time:number = 10;
	
	constructor(name: string){
    	this.name = name;
    }

	static calcDistance(speed: number): number {
    	return this.time * speend;
    }
}

const bird = new Bird('Nabi');
console.log(bird.name); // Nabi
bird.name = 'dori'; // Error: Cannot assign to 'name' because it is a read-only property.

console.log(Bird.calcDistance(5)) // 50

추상 클래스

  • class 앞에 abstract를 선언.
  • 인터페이스처럼 안에 추상 속성과 추상 메서드에 정의.
  • 실사용 가능한 메서드도 선언 가능.
  • 추상 메서드는 정의만 되어있고 상속받는 클래스에서 반드시 구현해야한다.
  • 추상 클래스는 인스턴스를 생성하지 않으므로 new 연산자로 호출하면 오류 발생.
abstract class Animal {
	abstract name: string;
    abstract getName(): string;
    private time: number = 10;
    
    calcDistance(speed: number): number {
    	return this.time * speed;
    }
}

class Parrot extends Animal {
	constructor(public name: string){
    	super();
    }
  	getName(): string {
    	return this.name;
    }
}

const parrot = new Parrot('Nabi');
console.log(parrot.name); // Nabi
console.log(parrot.getName()); // Nabi
console.log(parrot.calcDistance(5)); // 50

🍑오늘의 공부 일기

자바스크립트에서 없는 문법들이 있어서 아직 미숙하게 다루게 된다.
public, private, protected 접근 제한을 두면 수월하게 데이터를 관리할 수 있지 않을까라는 생각이 든다. 클래스 접근 제어자를 연습을 해보며 어떤 때에 이 부분을 적용해야할 지 생각하고 정리해봐야겠다.


참고 자료
https://yamoo9.gitbook.io/typescript/classes/abstract-class

profile
웹 프론트엔드 개발자

0개의 댓글