
T의 모든 프로퍼티를 읽기 전용(재할당 불가)으로 바꾸는 내장 제네릭 Readonly<T>를 이를 사용하지 않고 구현하세요.
예시
interface Todo {
title: string;
description: string;
}
const todo: MyReadonly<Todo> = {
title: "Hey",
description: "foobar",
};
todo.title = "Hello"; // Error: cannot reassign a readonly property
todo.description = "barFoo"; // Error: cannot reassign a readonly property
type MyReadonly<T> = {
readonly [Key in keyof T]: T[Key];
};
MyReadonly는 Object에 있는 모든 프로퍼티가 readonly 상태여야 한다.readonly는 프로퍼티 왼쪽에 쓰일 수 있다.(key in keyof T) 하여 readonly를 왼쪽에 넣어줌으로써, 모든 프로퍼티에 대해 readonly 상태를 만들 수 있다.readonly<T>
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
T의 모든 프로퍼티를 readonly 상태로 만들어 주는 유틸리티 타입type MyReadonly<T> = {
readonly [Key in keyof T]: T[Key];
};
interface Study {
typescript: string;
oop: string;
}
const myStudy: MyReadonly<Study> = {
typescript: "typechellenge",
oop: "oopstudy",
};
// Cannot assign to 'typescript' because it is a read-only property.(2540)
myStudy.typescript = "tc";
typescript, oop를 프로퍼티로 하는 Study(interface) 생성Readonly<T>와 동일한 MyReadonly<T>를 생성MyReadonly<Study>를 타입으로 하는 객체 myStudy 생성typescript 프로퍼티를 재 할당 하려고 하면 다음과 같은 2540 에러가 발생하는 것을 확인(모든 프로퍼티가 readonly이기 때문)readonly의 사용
interface, type (생략)
array
let myStudy: readonly string[] = ["oopstudy", "typechellenge"];
// Index signature in type 'readonly string[]' only permits reading.(2542)
myStudy[1] = "ts";
readonly string 배열 생성1번째 인덱스를 재 할당하는 경우 2542 에러 발생(readonly 이기 때문에 재 할당이 안됨)