본문 바로가기
Front-end/Typescript

[TypeScript] Class

by JiGyeong 2022. 8. 1.

아래와 같이 class 를 작성하면

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

const user1 = new Player('first','last','nick');

아래와 같이 javascript 로 나타내진다.

"use strict";
class Player {
    constructor(firstName, lastName, nickname) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.nickname = nickname;
    }
}
const user1 = new Player('first', 'last', 'nick');

abstract

다른 class가 상속 받을 수 있는 class. 다른 class 가 가져야 할 property 와 method를 명시할 수 있도록 도와준다.

abstract class는 new 키워드로 인스턴스를 생성할 수 없다.

 

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

    getFullName(){
        return `${this.firstName} ${this.lastName}`
    }
}

class Player extends User{
    
}

const user1 = new Player('first','last','nick');

console.log(user1.getFullName())

protected

인스턴스 만들어서 외부에선 호출이 불가능 하지만. 추상 객체를 상속 받은 자식객체에서는 사용 가능.

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

    abstract getNickName():void // abstract method 는 상속받는 곳에서 구현 필요.

}

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

const user1 = new Player('first','last','nick');

// 이건 안됨
user1.ninkname

private 은 추상클래스에서 인스턴스화 할 수 없음.

key:value type 정의

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

let dict:Words = {
    "key1":"ss"
}

Class 사용해보기

type Words = {
		// [2] 사용될 Properties Type을 정의할 수 있다.
    [key:string]: string
}

class Dict {
		// [1] Properties 만들고 초기화 할 수 있다.
    private words: Words
    constructor(){
        this.words = {}
    } 
		
		// Class를 Type 처럼 쓸수 있다.
    add(word:Word){
        if(this.words[word.term] === undefined){
            this.words[word.term] = word.def;
        }
    }

    def(term:string){
        return this.words[term];
    }
    
    deleteWord(term:string){
        delete this.words[term];
    }
    
    updateWord(word:Word){
        this.words[word.term] = this.words.def;
    }
}

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

const kimchi = new Word('kimchi','hot');
const dict = new Dict();

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

Dict Class의 add Method Parameter word가 Word Class 의 인스턴스이길 원할 때, word:Word 와 같이 쓸 수 있다.

 

 

이렇게 readonly를 주고 인스턴스에서 고치지 못하도록 할 수 있다.

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

word.term = “aaa” // error 남

 

static

class Dict {
	static hello(){
		return "hello"
	}
}

static으로 선언할 경우 Dict.hello() 처럼 호출이 가능해진다.

'Front-end > Typescript' 카테고리의 다른 글

[TypeScript] Interface  (0) 2022.08.01
[TypeScript] Generics  (0) 2022.07.25
[TypeScript] Basic Overview  (0) 2022.07.21