출처: 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로 만들어 버리는 방법이다...
'알고리즘 > Type Challenges' 카테고리의 다른 글
18 - Length of Tuple (0) | 2023.09.06 |
---|---|
14 - First of Array (0) | 2023.09.04 |
11 - Tuple to Object (0) | 2023.09.04 |
4 - Pick (0) | 2023.09.02 |
13 - Hello World (0) | 2023.08.22 |