as const
: const assertions 상수 어설션이라고 한다. TS 3.4에서 도입됨
as const
는 TypeScript에서 리터럴 값을 변경할 수 없는 상수로 고정할 때 사용하는 구문
이를 사용하면 객체, 배열, 기본 타입의 값을 readonly로 변환할 수 있다.
as const
를 사용한 예제const colors = ["red", "blue", "green"] as const;
colors
의 요소가 readonly가 되어 변경할 수 없게 된다. colors[0] = "black"; // Readonly라 변경 불가
as const
를 사용하지 않은 예제const colors = ["red", "blue", "green"];
colors
는 현재 string[]
colors
의 요소들은 현재 "red" | "blue" | "green"
중 하나가 아니라 모든 string 값을 가질 수 있다. const colors: string[] = ["red", "blue", "green"];
colors[0] = "black"; // 값 변경 가능
as const
객체const person = {
name: "Joe",
age: 28,
} as const;
person
타입은 다음과 같다. const person: {
readonly name: "Alice";
readonly age: 25;
}
name
과 age
는 변경 불가하다. as const
+ typeof
const directions = ["up", "down", "left", "right"] as const;
type Direction = typeof directions[number];
// "up" | "down" | "left" | "right"
directions[number]
를 사용하면 배열 요소를 유니온 타입으로 추출할 수 있다.