[노마드 리액트 스터디] 11일차 - 타입스크립트(4)

lisoh·2023년 2월 16일
0
post-thumbnail

4.0 Classes (11:12)

요약

  • 클래스를 사용할 때 타입스크립트와 자바스크립트의 다른점(this, property 접근 제어자)
  • 클래스의 상속 : 타입스크립트가 추상 클래스를 쓸 수 있게 해줌
  • 추상 클래스 : 직접 인스턴스를 만들지 못하는 클래스, 그러나 상속할 수 있다.
  • 추상 클래스에서 메소드를 구현하면 추상 클레스 안에서의 메소드, 메소드도 보호할 수 있음 접근제어자로.
  • 구현은 하지 않지만 call signature을 쓰면 추상 메소드 (코드가 없는)
  • 추상 메소드가 있는 경우, 추상 클래스를 상속받는 클래스에서 추상 메소드를 구현해주어야 함
  • 모든 것은 기본적으로 public. public 메소드, public 함수

타입스크립트로 객체지향 프로그래밍하기.
타입스크립트가 클래스 같은 객체 지향 기술을 구현할 수 있기 때문에 해볼겨.
C#이나 Java에 있는 개념들이 많이 등장한단다.

클래스, 인스턴스가 뭔지 알아야 듣기 쉽다네.

class Player {
	constructor(
    	private firstName:string,
        private lastName:string,
        public nickname:string
        ){}
 }
 
 const nico = new Player("nico", "las", "니꼬");

이렇게 쓰면 자바스크립트로 변환될때 privatepublic은 변환되지는 않지만 그래도 코드를 보호해줄거야. 그리고 자바스크립트에서도 잘 작동할거야.

추상 클래스
타입스크립트와 객체 지향 프로그래밍이 가지고 있는 훌륭한 것은 추상 클래스야.
추상 클래스는 다른 클래스가 상속받을 수 있는 클래스야.
하지만 추상 클래스는 직접 새로운 인스턴스를 만들 수는 없어.
오직 다른 곳에서 상속받을 수만 있는 클래스야.

abstract class User {
  constructor(
  		private firstName:string,
        private lastName:string,
        public nickname:string
       ){}
}

// Player 클래스는 User 클래스를 상속받는다.
class Player extends User{
}

const nico = new Player("nico", "las", "니꼬");

추상 클래스 안의 메소드와 추상 메소드(abstract method)

abstract class User {
  constructor(
  		private firstName:string,
        private lastName:string,
        public nickname:string
       ){}
  //추상 클래스 안에 들어가 있는 메소드 getFullName
  getFullName(){
    return `${this.firstName} ${this.lastName}`
  }
}

// Player 클래스는 User 클래스를 상속받는다.
class Player extends User{
}

const nico = new Player("nico", "las", "니꼬");

nico.getFullName()

추상 메소드를 만들려면, 메소드를 클래스 안에서 구현하지 않으면 돼.

return `${this.firstName} ${this.lastName}`

getFullName함수안에 쓰여진 이부분!! 을 안쓰면 돼.
메소드가 뭐냐고? 메소드는 클래스 안에 존재하는 함수야.

추상 클래스 안에서는 추상 메소드를 만들 수 있어.
근데, 메소드를 구현해서는 안되구, 메소드의 call signature만 써놔야해.

abstract class User {
  constructor(
  		private firstName:string,
        private lastName:string,
        private nickname:string
       ){}
  //추상 메소드 getNickName
  abstract getNickName():void
  //추상 클래스 안에 들어가 있는 메소드 getFullName
  getFullName(){
    return `${this.firstName} ${this.lastName}`
  }
}

위에 보면 추상메소드 getNickName은 메소드의 call signature만 가지고 있어.
추상 메소드는 네가 추상 클래스를 상속받는 모든 것들이 구현을 해야하는 메소드를 의미해.

abstract class User {
  constructor(
  		private firstName:string,
        private lastName:string,
        private nickname:string
       ){}
  //추상 메소드 getNickName
  abstract getNickName():void
  //추상 클래스 안에 들어가 있는 메소드 getFullName
  getFullName(){
    return `${this.firstName} ${this.lastName}`
  }
}

class Player extends User {
  getNickName() {
    console.log(this.nickname)
  }
}

위처럼 만약에 네가 property를 private으로 만들면, 네가 그 클래스를 상속했을지라도 (여기서는 Player) nickname을 불러낼 수가 없징. 접근할 수가 없어.

만약 property가 private으로 설정되어 있다면, 당연히 인스턴스 밖에서 접근할 수가 없고, 다른 자식 클래스에서도 접근할 수 없어.
근데 property가 protected로 설정되어 있다면, 다른 자식 클래스에서도 쓸 수 있지.

4.1 Recap (15:08)

해시맵. 해싱 알고리즘을 쓰는 해시맵. 약간 사전같은거야.

type Words = {
  	[key:string]: string
}
//Words 타입이 string만을 property로 가지는 오브젝트라는 걸 말해줌
//제한된 양의 property 혹은 Key를 가지는 타입을 정의해주는 방법이야.
//property의 이름은 모르지만, 타입만을 알 때 이걸 써.

let dict : Words = {
  	"potato":"food"
}

class Dict {
  	private words: Words
  //이건 Constructor에서 직접 초기화 되지 않는 Property야
  //words를 initializer 없이 선언해주고 
  // Constructor에서 수동으로 초기화시켜줄거야.
  	constructor(){
      	this.words = {}
    }
    add(word:Word){ //클래스를 타입으로 썼어!!
      if(this.words[word.term] === undefined){
        this.words[word.term] = word.def
        // 여기는 [word.term]인데
      }
    }
    def(term:string){
      return this.words[term]
      // 여기는 왜 [term]인가?
    }
}

class Word {
	constructor(
		public term:string,
        public def : string
    ) {}
}

const kimchi = new Word("kimchi", "한국의 음식");

const dict = new Dict()

dict.add(kimchi);
dict.def("kimchi");

dict.add("pizza","이탈리아 음식")

궁금한 것.

  1. class와 인스턴스가 무엇이었지?
  2. const kimchi처럼 미리 넣어둔 변수가 아니라 add함수로 바로 단어와 뜻을 함께 넣으려면 어떻게 해야하지?
    dict.add({term:"pizza", def:"이탈리아의 음식"})
    //객체 리터럴이나 클래스 인스턴스를 넣어야 Word 타입으로 추론이 됨
  3. this.words[word.term]가 뭐지?
    동적 프로퍼티
    this.words."kimchi"나 this.words.hasOwnPropery(word.term)와 같은 것.
profile
프론트엔드 개발자를 꿈꾸는 개발초보 호랑이

0개의 댓글