제주도랏맨 2023. 9. 2. 23:08

 

출처: Type Challenges, https://github.com/type-challenges/type-challenges/blob/main/README.ko.md

 

7 - Readonly

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 [P in keyof T]: T[P]
}

 

typescript에는 기본적으로 readonly 속성을 지정할 수 있게 해준다.

Type 내부에 있는 키들을 가져와서 P라고 지정하고 key - value 형태로 다시 가져오는 모습이다.

그런데 앞에 readonly 속성을 붙여줘서 모든 속성을 readonly로 만들어 버리는 방법이다...