Frontend/Javascript
[TypeScript] Class에 대해 알아보자
돌잡이개발자
2022. 6. 14. 11:33
TypeScript는 ES6에서 도입된 클래스 문법을 지원하며 보다 강력한 기능을 제공한다.
클래스 문법에서 타입스크립트 적용하기
class BadGreeter {
// error: Property 'name' has no initializer and is not definitely assigned in the constructor.
name: string;
}
class GoodGreeter {
name: string;
// 생성자에서 클래스 필드 초기화하기
constructor() {
this.name = "hello";
}
}
class OKGreeter {
// Not initialized, but no error
name!: string;
}
접근 제어자
접근 제어자를 통해 접근 가능한 범위를 설정하고 각 속성에 데이터 타입을 지정할 수 있다.
구분 | 선언한 클래스 내 | 상속받은 클래스 내 | 인스턴스 |
private | O | X | X |
protected | O | O | X |
public | O | O | O |
class Player {
constructor (
// private: 클래스 내부에서만 접근 가능
private firstName: string,
private lastName: string,
// public: 클래스 외부에서 접근 가능
public nickname: string,
// protected: player 클래스를 포함한 서브 클래스에서만 접근 가능
protected age: number,
) {}
}
const nico = new Player("sophie", "lee", "jelly");
// error: Property 'firstName' is private and only accessible within class 'Player'.
sophie.firstName
상속
서브 클래스는 constructor를 상속 받은 수퍼 클래스의 생성자를 덮어 쓸 수 있다.
이 때 super()를 사용해 수퍼 클래스의 생성자에 요구되는 인자를 전달해야 한다.
class E_Book extends Book {
paper_type = '스크린';
constructor(
title:string,
author:string,
pages:number,
public is_downloadable:boolean
){
// 수퍼 클래스 constructor를 덮어쓰기 위해서는 super() 실행이 필요합니다.
super(title, author, pages);
this.is_downloadable = is_downloadable;
}
}
추상 클래스
추상 클래스는 정의만 되어 있고 상속하는 클래스에서 해당 추상 메서드를 통해 구현해야 한다.
// 추상 클래스: 다른 클래스가 상속 받을 수 있는 클래스
abstract class User {
constructor (
private firstName: string,
private lastName: string,
public nickname: string
) {}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
// Error: 새로운 인스턴스를 직접 만들 수 없음
const sophie = new User("sophie", "lee", "jelly");
const sophie = new Player("sophie", "lee", "jelly");
sophie.getFullName()
abstract class User {
constructor (
private firstName: string,
private lastName: string,
private nickname: string
) {}
// 추상 메서드
abstract getNickName(): void
// 추상 클래스에서 메서드 구현
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
getNickName() {
// error: Property 'nickname' is private and only accessible within class 'User'.
console.log(this.nickname)
}
}
// To fix error
abstract class User {
constructor (
protected firstName: string,
protected lastName: string,
protected nickname: string
) {}
abstract getNickName(): void
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
참고자료
https://www.typescriptlang.org/docs/handbook/2/classes.html#public
반응형