포시코딩

[TypeScript][노마드코더] #4 CLASSES AND INTERFACES(3) 본문

JavaScript

[TypeScript][노마드코더] #4 CLASSES AND INTERFACES(3)

포시 2023. 1. 22. 20:25
728x90

readonly

 

TypeScript

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

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 Word {
    constructor (
        public term: string, 
        public def: string
    ) {}
}

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

const dict = new Dict();

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

위 코드에서 Word의 term과 def가 public이기 때문에 Dict의 add가 

word.term, term.def 에 접근할 수 있다.

 

하지만

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

kimchi.def = '중국의 음식';

public이라 이렇게 할 가능성이 존재한다.

어떻게 하면 값을 보여주면서 수정은 불가능하게 할 수 있을까?

 

readonly 속성을 부여하면 된다.

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

 

type 사용 방법

interface에 대해 알아보기 전에

먼저 TypeScript에서 type 키워드를 통해 만들 수 있는 type들을 확인해보자

 

Object의 모양을 만들어 사용하는 방법

type Player = {
    nickname: string, 
    healthBar: number
}

const nico: Player = {
    nickname: "nico", 
    healthBar: 10
}

이렇게 사용할 수 있고 만드는 과정에서도 자동완성 기능이 잘 작동하는걸 알 수 있다.

 

return 받는 type으로 사용하는 방법

type Food = string;

const kimchi: Food = "delicious"

 

alias(대체명)로 사용하는 방법

type Nickname = string
type HealthBar = number

type Player = {
    nickname: Nickname, 
    healthBar: HealthBar
}

 

지정된 옵션으로만 제한하는 경우

type Team = 'red' | 'blue' | 'yellow';

type Player = {
    nickname: string, 
    team: Team
}

이처럼 type은 굉장히 여러 방면으로 쓰일 수 있다.

 

interface

type Team = 'red' | 'blue' | 'yellow';
type Health = 1 | 5 | 10;

type Player = {
    nickname: string,
    team: Team, 
    health: Health
}

const nico: Player = {
    nickname: 'nico', 
    team: 'yellow', 
    health: 10
}

이 코드에서 Player type을 interface로 바꿔보자

type Team = 'red' | 'blue' | 'yellow';
type Health = 1 | 5 | 10;

// type Player = {
interface Player {
    nickname: string,
    team: Team, 
    health: Health
}

const nico: Player = {
    nickname: 'nico', 
    team: 'yellow', 
    health: 10
}

몇글자만 바꿔줬을뿐인데 바로 바뀌었다.

더군다나 하단의 코드를 구현하는데에서는 아무것도 바뀌지 않았고 잘 작동한다.

 

인터페이스는 단 한가지 용도를 가지고 있다.

TypeScript에게 Object의 모양을 특정(설명)해주기 위한 용도

 

사용 예시

interface User {
    name: string
}

interface Player extends User {
}

const nico: Player = {
    name: 'nico'
}

 

만약 type을 쓴다면 아래와 같이 써야할 것이다.

type User = {
    name: string
}

type Player = User & {
}

const nico: Player = {
    name: 'nico'
}

 

interface의 특징 중 하나로 property를 축적시킬 수 있다.

interface User {
    name: string
}

interface User {
    lastName: string
}

interface User {
    health: number
}

const nico: User = {
    name: 'nico', 
    lastName: 'hi', 
    health: 10
}

위 기능은 type에서 할 수 없다.

728x90