TypeScript로 객체지향 프로그래밍하기
class
class Player {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
}
const nico = new Player("nico", "las", "니꼬")
타입스크립트에서 이렇게 constructor의 타입을 선언해주면 자바스크립트에서 this.firstName = firstName; 이 부분을 따로 안 해주어도 된다.

이 부분이 자동적으로 컴파일 되어서 편리하다!
하지만 이렇게 class 내에서 private, public 등의 설정은 타입스크립트 내의 기능이기 때문에 자바스크립트로 컴파일되지 않는다.
추상 클래스(Abstract Class)
다른 클래스가 상속받을 수 있는 클래스
상속받는 다른 클래스가 가질 property와 메소드를 지정한다.
abstract class User {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
}
class Player extends User {
}
이러한 추상 클래스는 인스턴스를 만들 수 없다.
const nico = new User("nico", "las", "니꼬") // 추상 클래스는 인스턴스를 만들 수 없기 때문에 오류가 난다.
따라서 추상 클래스는 오직 다른 곳에서 상속받을 수만 있고 인스턴스를 만들지 못하는 클래스이다.
추상 메소드(Abstract)
추상 클래스를 상속받는 모든 자식 클래스들이 구현해야 하는 메소드
구현은 어떻게 되어도 상관없지만 구현이 되기를 원하는 메소드를 지정하는 것이다.
추상 메소드를 만들려면 메소드를 구현하는 것이 아니라 메소드의 call signature를 정의해야 한다.
abstract class User {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
abstract getNickName(): void //리턴 값의 타입을 지정한 call signature, 추상 메소드이다.
getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User { //추상 메소드가 있기 때문에 getNickName이 구현되지 않았다고 오류가 뜰 것.
}
추상 클래스 내의 private의 경우
abstract class User {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
const nico = Player("nico", "las", "니꼬");
nico.getFullName();
nico는 Player class를 사용했고 Palyer class는 User 추상 클래스를 상속받았기 때문에 nico.getFullName이 정상 작동한다.
abstract class User {
constructor(
private firstName: string,
private lastName: string,
private nickName: string
) {}
private getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
const nico = Player("nico", "las", "니꼬");
nico.getFullName(); //오류 발생
하지만 함수를 private로 설정할 경우 오류가 난다. property를 private로 만든 경우 그 클래스를 상속받는 클래스 일지라도 그 property에 접근할 수 없다. 또한 User를 상속받은 Player에서 this.nickName을 통해 접근할 수 없다.
private의 경우 인스턴스 밖에서 접근할 수 없고, 다른 자식 클래스에서도 접근할 수 없다. 외부에서는 보호되지만 자식 클래스에서도 property를 사용하길 원하는 경우 private가 아닌 protected를 사용해야 한다.
protected
abstract class User {
constructor(
protected firstName: string,
protected lastName: string,
protected nickname: string
) {}
protected getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
getNickName(){
console.log(this.nickname); //protected이기 때문에 접근 가능
}
}
const nico = Player("nico", "las", "니꼬");
nico.firstName //오류 발생. 클래스 밖에서는 접근할 수 없음.
protected의 경우 상속 받은 자식 클래스에서는 접근이 가능하지만 클래스 밖에서는 접근할 수 없다.
따라서 접근 가능한 위치는
선언한 클래스 내부 | 상속받은 클래스 내부 | 인스턴스 | |
private | ㅇ | x | x |
protected | ㅇ | ㅇ | x |
public | ㅇ | ㅇ | ㅇ |
해시 맵 만들기(단어 사전)
사전에 새 단어를 추가하고, 단어를 찾고, 단어를 삭제하는 메소드를 만들 것이다.
type Words = {
[key: string]: string
}
class Dict {
private words: Words
}
이 경우 Wods의 property는 모두 string 타입이어야 한다는 조건을 만든 것이 바로 [key: string] 부분이다. 조건 이름은 key 이든 x이든 아무거나 상관없다. 이것은 제한된 양의 property 혹은 key를 가지는 타입을 정의해 주는 방법이다.
type Words = {
[key: string]: string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
}
class Word{
constrcutor(
public term:string,
public def :string
) {}
}
class Dict에서 words를 constructor 내부에서 선언하지 않고 외부에서 선언한 뒤 (initializer 없이 선언) constructor에서 수동으로 초기화시켜주었다. 왜냐하면 constructor에 word를 인자로 넣어 constructor가 지정하지 않도록 하기 위해서 이 방법을 사용한다.
이제 메소드를 만들어 보자.
type Words = {
[key: string]: string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
add(word: Word){ //클래스 Word를 타입처럼 사용할 수 있다.
if(this.words[word.term] === undefined){ //주어진 단어가 사전에 존재하지 않을 때
this.words[word.term] = word.def;
}
}
def(term: string){
return this.words[term];
}
}
class Word{
constructor(
public term:string,
public def :string
) {}
}
이런 방식으로 다양한 메소드를 만들 수 있다.
'개발 공부 > TypeScript' 카테고리의 다른 글
TypeScript #4 [readonly, 추상화, 인터페이스] (0) | 2022.08.01 |
---|---|
TypeScirpt#2 [함수, call signatures, overloading, 다형성, 제네릭] (0) | 2022.07.27 |
TypeScript #1 [type] (0) | 2022.07.25 |
TypeScript로 객체지향 프로그래밍하기
class
class Player {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
}
const nico = new Player("nico", "las", "니꼬")
타입스크립트에서 이렇게 constructor의 타입을 선언해주면 자바스크립트에서 this.firstName = firstName; 이 부분을 따로 안 해주어도 된다.

이 부분이 자동적으로 컴파일 되어서 편리하다!
하지만 이렇게 class 내에서 private, public 등의 설정은 타입스크립트 내의 기능이기 때문에 자바스크립트로 컴파일되지 않는다.
추상 클래스(Abstract Class)
다른 클래스가 상속받을 수 있는 클래스
상속받는 다른 클래스가 가질 property와 메소드를 지정한다.
abstract class User {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
}
class Player extends User {
}
이러한 추상 클래스는 인스턴스를 만들 수 없다.
const nico = new User("nico", "las", "니꼬") // 추상 클래스는 인스턴스를 만들 수 없기 때문에 오류가 난다.
따라서 추상 클래스는 오직 다른 곳에서 상속받을 수만 있고 인스턴스를 만들지 못하는 클래스이다.
추상 메소드(Abstract)
추상 클래스를 상속받는 모든 자식 클래스들이 구현해야 하는 메소드
구현은 어떻게 되어도 상관없지만 구현이 되기를 원하는 메소드를 지정하는 것이다.
추상 메소드를 만들려면 메소드를 구현하는 것이 아니라 메소드의 call signature를 정의해야 한다.
abstract class User {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
abstract getNickName(): void //리턴 값의 타입을 지정한 call signature, 추상 메소드이다.
getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User { //추상 메소드가 있기 때문에 getNickName이 구현되지 않았다고 오류가 뜰 것.
}
추상 클래스 내의 private의 경우
abstract class User {
constructor(
private firstName: string,
private lastName: string,
public nickname: string
) {}
getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
const nico = Player("nico", "las", "니꼬");
nico.getFullName();
nico는 Player class를 사용했고 Palyer class는 User 추상 클래스를 상속받았기 때문에 nico.getFullName이 정상 작동한다.
abstract class User {
constructor(
private firstName: string,
private lastName: string,
private nickName: string
) {}
private getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
const nico = Player("nico", "las", "니꼬");
nico.getFullName(); //오류 발생
하지만 함수를 private로 설정할 경우 오류가 난다. property를 private로 만든 경우 그 클래스를 상속받는 클래스 일지라도 그 property에 접근할 수 없다. 또한 User를 상속받은 Player에서 this.nickName을 통해 접근할 수 없다.
private의 경우 인스턴스 밖에서 접근할 수 없고, 다른 자식 클래스에서도 접근할 수 없다. 외부에서는 보호되지만 자식 클래스에서도 property를 사용하길 원하는 경우 private가 아닌 protected를 사용해야 한다.
protected
abstract class User {
constructor(
protected firstName: string,
protected lastName: string,
protected nickname: string
) {}
protected getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
getNickName(){
console.log(this.nickname); //protected이기 때문에 접근 가능
}
}
const nico = Player("nico", "las", "니꼬");
nico.firstName //오류 발생. 클래스 밖에서는 접근할 수 없음.
protected의 경우 상속 받은 자식 클래스에서는 접근이 가능하지만 클래스 밖에서는 접근할 수 없다.
따라서 접근 가능한 위치는
선언한 클래스 내부 | 상속받은 클래스 내부 | 인스턴스 | |
private | ㅇ | x | x |
protected | ㅇ | ㅇ | x |
public | ㅇ | ㅇ | ㅇ |
해시 맵 만들기(단어 사전)
사전에 새 단어를 추가하고, 단어를 찾고, 단어를 삭제하는 메소드를 만들 것이다.
type Words = {
[key: string]: string
}
class Dict {
private words: Words
}
이 경우 Wods의 property는 모두 string 타입이어야 한다는 조건을 만든 것이 바로 [key: string] 부분이다. 조건 이름은 key 이든 x이든 아무거나 상관없다. 이것은 제한된 양의 property 혹은 key를 가지는 타입을 정의해 주는 방법이다.
type Words = {
[key: string]: string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
}
class Word{
constrcutor(
public term:string,
public def :string
) {}
}
class Dict에서 words를 constructor 내부에서 선언하지 않고 외부에서 선언한 뒤 (initializer 없이 선언) constructor에서 수동으로 초기화시켜주었다. 왜냐하면 constructor에 word를 인자로 넣어 constructor가 지정하지 않도록 하기 위해서 이 방법을 사용한다.
이제 메소드를 만들어 보자.
type Words = {
[key: string]: string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
add(word: Word){ //클래스 Word를 타입처럼 사용할 수 있다.
if(this.words[word.term] === undefined){ //주어진 단어가 사전에 존재하지 않을 때
this.words[word.term] = word.def;
}
}
def(term: string){
return this.words[term];
}
}
class Word{
constructor(
public term:string,
public def :string
) {}
}
이런 방식으로 다양한 메소드를 만들 수 있다.
'개발 공부 > TypeScript' 카테고리의 다른 글
TypeScript #4 [readonly, 추상화, 인터페이스] (0) | 2022.08.01 |
---|---|
TypeScirpt#2 [함수, call signatures, overloading, 다형성, 제네릭] (0) | 2022.07.27 |
TypeScript #1 [type] (0) | 2022.07.25 |