JSTS

[TS] 4. 이넘, 클래스

Jaaaay 2022. 7. 7. 17:42

이넘

이넘(Enums)은 특정 값들의 집합을 의미하는 자료형이다.

숫자형 이넘

별도의 이넘 형식을 지정해주지 않으면 숫자형 이넘으로 설정된다.

처음 값을 0 기준 1씩 증가하는 값으로 초기화돼 있다.

enum Shoes {
    Nike,
    Adidas
}

var myShoes = Shoes.Nike
console.log(myShoes); // 0

문자형 이넘

enum Shoes {
    Nike = '나이키',
    Adidas = '아디다스'
}

var myShoes = Shoes.Nike
console.log(myShoes); // '나이키'

이넘 활용 사례

// 예제
enum Answer {
    Yes = 'Y',
    No = 'N'
}

function askQuestion(answer: Answer) {
    if(answer === Answer.Yes){
        console.log('정답');
    }
    if (answer === Answer.No){
        console.log('오답');
    }
}

askQuestion(Answer.Yes);

이넘에서 제공하는 값만 넘기는 코드를 작성. 하드 코딩하는 방식보다 이렇게 하는 편이 수정 등에 용이함.


클래스

JS ES6 부터 클래스 문법을 지원

// JS class 예시
class Person {
    // 클래스 로직
    constructor(name, age) {
        console.log('생성 되었습니다');
        this.name = name;
        this.age = age;
    }
}

var seho = new Person('세호', 30); // 생성 되었습니다.
console.log(seho);

타입스크립트의 클래스 문법

class Person {
    private name: string;
    public age: number; 
    readonly log: string;

    constructor(name: string, age: number){
        this.name = name;
        this.age = age;
    }
}