07. Readonly
문제
Implement the built-in Readonly<T>
generic without using it.
Constructs a type with all properties of T
set to readonly
, meaning the properties of the constructed type cannot be reassigned.
For example:
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
풀이
너무 간단하다!
// 0. 시작
type MyReadonly<T> = ...
// 1. 결과값은 {} 형태를 띄어야한다.
type MyReadonly<T> = {}
// 2. T 의 키-밸류를 이용해야한다.
type MyReadonly<T> = { [K keyof T]: ...}
// 3. T 의 모든 프로퍼티들을 돌면서 반복을 돌아야한다. (in 을 사용하면 반복)
type MyReadonly<T> = { [K in keyof T]: ... }
// 4. T 의 키값을 이용해서 밸류를 결정한다.
type MyReadonly<T> = { [K in keyof T]: T[K] }
// 5. readonly 속성을 준다.
type MyReadonly<T> = { readonly [K in keyof T]: T[K] }
기본문제에서 계속 보게 되는 그 주제... Mapped Type
을 한번 더 보고 가자!
Last updated
Was this helpful?