as const(const assertions)

Hunter Joe·2025년 2월 13일
0

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;
}
  • person의 속성인 nameage는 변경 불가하다.

as const + typeof

const directions = ["up", "down", "left", "right"] as const;
type Direction = typeof directions[number]; 
// "up" | "down" | "left" | "right"
  • directions[number]를 사용하면 배열 요소를 유니온 타입으로 추출할 수 있다.

언제 사용하면 좋을까

  1. 불변성을 유지하고 싶은 경우
  2. 객체나 배열의 값을 리터럴 타입으로 고정하고 싶은 경우
  3. 유니온 타입을 만들 때
profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글

관련 채용 정보