[typescript] Enum & Literal

Enum

  • 사용법은 자바와 동일
// Enum 변수에 따로 값을 지정해 주지 않으면 0부터 값이 주어짐
enum Grade {
    A,  // -> 값: 0
    B = 'B', 
    C = 'C'
}  

interface Student {
    readonly name: string,
    age: number,
    address?: string, //null 허용
    grade: Grade //Enum 타입을 받음
}

function showStudentGrade(student: Student):void {
    console.log(`${student.name}(${student.age}) got ${student.grade}`);
}

showStudentGrade({
    name: 'woogie', 
    age: 28, 
    grade: Grade.A
});
-> woogie(28) got 0

showStudentGrade({
    name: 'woogie', 
    age: 28, 
    grade: Grade.B
});
-> woogie(28) got B

Literal

  • enum 타입과 같은 효과를 내면서 코드를 간결하게 함
interface Cat {
    name: string,
    age: number,
    color: 'white' | 'black' | 'gray'
}

function showCat(cat: Cat):void {
    console.log(`${cat.name}(${cat.age}) has ${cat.color} hair.`);
}

showCat({
    name: 'nyao',
    age: 2,
    color: 'white'
//color: 'blue'
//오류발생
//Type '"blue"' is not assignable to type '"white" | "black" | "gray"'
});
-> nyao(2) has white hair.

links

social