- 해당 값의 속성을 읽기 전용으로 설정해주는 타입시스템 기능입니다.
- 함수가 매개변수로 받는 값을 변경 없이 그대로 사용해야할 때 적합합니다.
- 외부에서 호출이 가능하지만 값의 변경은 불가능하므로, 값을 변경하기 위해서는 값을 초기화해줘야 합니다.
interface Todo{
readonly title: string;
body: string;
}
const todo: Todo = {
title: "중요한 일정",
body: "병원가기"
}
todo.title = "오늘 안에 해야할 일";
todo.body = "옷정리";
// Cannot assign to 'title' because it is a read-only property.
Readonly
Readonly은 집합의 모든 프로퍼티 읽기 전용(readonly)으로 설정한 타입을 생성하기 때문에 생성된 타입의 프로퍼티를 재할당이 불가능합니다.
예시
interface Todo{
title: string;
body: string;
}
const todo: Readonly<Todo> = {
title: "중요한 일정"
body: "병원가기"
}
todo.title = "오늘 안에 해야할 일"
// Cannot assign to 'title' because it is a read-only property.
만약 배열을 읽기 전용으로 생성한다면 ReadonlyArray<Type>을 사용하면 됩니다.
let numArray: ReadonlyArray<number> = [1, 2, 3];
console.log(numArray[1]); // 2
numArray.push(4);
// Property 'push' does not exist on type 'readonly number[]'.
numArray[0] = 10;
// Index signature in type 'readonly number[]' only permits reading.
참조
https://www.typescriptlang.org/ko/docs/handbook/utility-types.html#readonlytype
Documentation - Utility Types
Types which are globally included in TypeScript
www.typescriptlang.org
https://radlohead.gitbook.io/typescript-deep-dive/type-system/readonly
읽기 전용(readonly) - TypeScript Deep Dive
기본적으로 readonly는 내가 속성을 변경하지 못함을 보장하지만, 객체를 다른 사람에게 넘길 경우에는 이것이 보장되지 않고 그 다른 사람은 객체의 속성을 변경할 수 있습니다 (타입 호환성 문
radlohead.gitbook.io
'TypeScript > TS' 카테고리의 다른 글
Mapped Types (0) | 2022.11.09 |
---|---|
Utility Types(유틸리티 타입) - Partial, Required, Pick, Omit (0) | 2022.10.29 |