리터럴 타입은 집합 타입의 더 구체적인 하위 타입이다. TS에는 2가지 리터럴 타입으로 문자열과 숫자가 있고, 이를 사용하면 문자열이나 숫자에 정확한 값을 지정할 수 있다.
var
or let
으로 변수 선언 시 : 변수의 값이 변경될 가능성이 있음const
로 변수 선언 시 : 변수의 값이 절대 변경되지 않음// 문자열이 아닌 "Hello World"로 타입을 정함
const helloWorld = "Hello World";
// 문자열이라고 선언 함
let hiWorld = "Hi World";
문자열 리터럴 타입은 유니언 타입, 타입 가드, 타입 별칭과 잘 결합된다. 이런 기능을 함께 사용하여 문자열로 enum과 비슷한 형태를 갖출 수 있다.
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement{
animate(dx: number, dy: number, easing: Easing) {
if(easing == "ease-in") {
//...
} else if (easing === "ease-out") {
} else if (easing === "ease-in-out") {
} else {
// 누군가가 타입을 무시하면 else 구문이 실행됨
}
}
}
let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy");
허용된 세 개의 문자열이 아닌 다른 문자열 사용 시, 오류가 발생한다.
문자열 리터럴 타입은 오버로드를 구별하는 것과 같은 방법으로 쓰일 수 있다.
function createElement(tagName: "img"):HTMLImageElement;
function createElement(tagName: "input"): HTMLImageElement;
// ...
function createElement(tagName: string): Element {
// ...
}
문자열 리터럴과 같은 역할을 하는 숫자형 리터럴 타입도 있다.
function rollDice(): 1 | 2 | 3 | 4 | 5 | 6;
return (Math.floor(Math.random() * 6) +1) as 1 | 2 | 3 | 4 | 5 | 6;
}
const result = rollDice();
주로 설정값을 설명할 때 사용된다.