[TypeScript] Class

jr_necki·2022년 8월 23일
0

TypeScript

목록 보기
6/7
post-thumbnail

✔ Class

타입 스크립트로 클래스를 만들어보자.

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

const nekci = new Player("necki","hong","네키");

클래스 생성자에 properties와 타입을 지정해주면된다.

자바스크립트로는 이렇게 코드가 쓰여진다.

class Player {
    constructor(firstName, lastName, nickname) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.nickname = nickname;
    }
}

자바스크립트처럼 this.firstName이런식으로 하지 않아서 비교적 간편하다.
또한 private이나 public은 타입스크립트에서만 쓰이는것을 볼 수 있다.

necki.firstName // 에러남!
nekci.nickname // 괜찮음.

따라서, 타입스크립트는 private인 firstName에 접근할 수 없도록 조치를 취해준다.

✔ Abstract

추상클래스는 다른 클래스가 상속받을 수 있는 클래스이다. 그러나 직접 새로운 인스턴스를 만들 수는 없다.

User 추상 클래스와, 이를 상속받는 Player클래스를 만들어보자.

User로 새로운 클래스를 만드는 것은 불가능한 것을 볼 수 있다.

✔ Method

추상 클래스 안에 메서드를 넣는 것도 가능하다.
풀네임을 반환하는 getFullName메서드를 만들어보자.

abstract class User {
    constructor(
        private firstName:string,
        private lastName:string,
        public nickname:string
    ){}
    getFullName(){
        return `${this.firstName} ${this.lastName}`;
    }
}

아까 만들었던 necki객체에서 접근가능하다.

nekci.getFullName();

그러나 getFullName이 private이라면 접근 불가하다.

✔ Abstract Method

추상메서드는, 메서드를 직접 넣어서는 안되고 콜만 적어두어야한다.

 abstract getNickName():void

그렇게 되면, 추상 메서드를 상속한 클래스에서는 해당 추상메서드를
implement 즉 구현해주어야한다.

그러나 상속 받았다고 하더라도 private property는 여전히 접근할 수 없다.
외부 접근을 막고 자식클래스에서는 사용하고 싶다면 private이 아닌 protected를 사용하자

✔ 위에 것들을 응용하여 사전 만들기

word 라는 콜과
Dict, Word 라는 클래스를 생성하고,
Dict 클래스에는 사전에 단어를 추가 할 수 있는 메서드를 만들어 보자.

//call
type Words = {
    [key:string] : string
}

// class
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] // 뜻을 반환
    }
}

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

    }
}

const naruto = new Word("naruto","닌자가 나오는 만화")
const dict = new Dict();
dict.add(naruto);
dict.def("naruto")
profile
슉슉슉

0개의 댓글