[TS] readonly와 const, as const

heyday.xz·2024년 8월 4일
2
post-thumbnail

질문을 받으니까 헷갈렸던 readonly와 const, as const의 차이점을 정리해본다.

readonly

readonly 키워드는 객체 프로퍼티나 배열 요소를 변경할 수 없도록 하는 데 사용된다.

예제

interface Person {
  readonly name: string;
  age: number;
}

const person: Person = { name: "John", age: 30 };
// person.name = "Peter"; // Error: Cannot assign to 'name' because it is a read-only property.
person.age = 31; // OK

여기서 name 프로퍼티는 읽기 전용이므로 값을 변경할 수 없다.

const

const는 변수 선언 시 사용되어 변수를 재할당할 수 없게 만든다.
그러나 const로 선언된 객체나 배열의 내부 프로퍼티는 변경할 수 있다!

예제

const arr = [1, 2, 3];
// arr = [4, 5, 6]; Error: Assignment to constant variable.
arr.push(4); // OK
console.log(arr); // [1, 2, 3, 4]

const obj = { name: "Alice" };
// obj = { name: "Mike" }; // Error: Assignment to constant Variable.
obj.name = "Mike"; // OK
console.log(obj); // { name: "Mike" }

as const

as const는 객체 리터럴을 불변으로 만드는 데 사용된다.
객체의 모든 프로퍼티를 읽기 전용으로 만들고, 가능한 가장 좁은 타입(리터럴 타입)을 지정한다.

예제

const directions = {
  Up: "UP",
  Down: "DOWN",
  Left: "LEFT",
  Right: "RIGHT"
} as const;

// directions.Up = "Down"; // Error: Cannot assign to 'Up' because it is a read-only property.

type Direction = typeof directions[keyof typeof directions];

let move: Direction = directions.Up;
console.log(move); // "UP"

as const 를 사용하여 directions 객체의 모든 프로퍼티를 읽기 전용으로 만들었기 때문에, 내부 프로퍼티 변경이 불가능하다.
각 프로퍼티의 타입을 문자열 리터럴 타입으로 지정한다.

0개의 댓글