타입 스크립트 - 클래스

Seong·2022년 11월 10일
0

Type_Script

목록 보기
4/7

JS와 TS에서도 객체지향언어처럼 코딩을 할 수 있다.

자바스크립트에서 클래스의 생성자를 생성할려면 this.매개변수 를 사용해야했다.
타입스크립트에서는 좀더 간편하게 설정할 수 있다.

자바스크립트

클래스

class Plaryer {
    constructor(first_name, last_name, nickname) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.nickname = nickname;
    }
}

= 타입스크립트

class Plaryer {
  constructor(
    private first_name:string,
    private last_name:string,
    public nickname:string,
  ){}
}
  • 타입스크립트의 접근지정자(private, public 등등)은 자바스크립트에서는 사용되지 않는다

타입스크립트의 추상화

abstract class 로 추상클래스로 설정 할 수 있음
(
추상클래스:다른 클래스가 상속받을수 있으면서 인스턴스를 생성할 수 없는 클래스
추상메소드:상속받는 클래스에서 구현해야하는 메서드
)

abstract class User {  //추상클래스
  constructor(
    private first_name: string,
    private last_name: string,
    protected nickname: string,
  ) {}
  abstract getNickname():void //추상매소드
  getFullName() {
    return `${this.first_name} ${this.last_name}`
  }
}


class Plaryer extends User {
  getNickname(){
    console.log(this.nickname);
  }
}

const seong = new Plaryer('SeungYoung', 'Seong', 'netban');
seong.getFullName();

Hash를 이용한 단어사전 만들기

//사전
type Words = { [key: string]: string }  //Hash Key - Value

class Dict {
  private words: Words
  constructor() {
    this.words = {}
  }
  add(word: Word) {       //넣기
    if (this.words[word.term] === undefined) {
      this.words[word.term] = word.def;
    }
  }
  def(term: string) {        //찾기
    return this.words[term];
  }
  delete(term: string) {  //지우기
    if (this.words[term]) {
      delete this.words[term];
    }
  }
  all() { //전부보기
    for (let i in this.words){
      console.log(`${i} : ${this.words[i]}`)
    }
  }
}

class Word {
  constructor(
    public term: string,
    public def: string,
  ) { }
}
const express = new Word("express", "JS기반 백엔드 프레임워크");
const next = new Word('next.js', 'JS기반 프런트 프레임워크');
const spring = new Word("spring","JAVA기반 백엔드 프레임워크")

const dict = new Dict();

dict.add(express);  //넣기
dict.add(next);  //넣기
dict.add(spring);  //넣기
dict.def('express') //찾기
dict.delete('spring') //지우기
dict.all(); //전부 보기

JAVA에서 객체지향언어 프로그래밍을 배웠다면 이해하는데에는 큰 무리가 없을듯하다.

profile
메모장

0개의 댓글