프로그래밍/TypeScript
Readonly type 구현
카카수(kakasoo)
2023. 2. 15. 23:59
반응형
GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge
Collection of TypeScript type challenges with online judge - GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge
github.com
Implement a generic MyReadonly2<T, K> which takes two type argument T and K.
K specify the set of properties of T that should set to Readonly. When K is not provided, it should make all properties readonly just like the normal Readonly.
For example,
interface Todo {
title: string
description: string
completed: boolean
}
const todo: MyReadonly2<Todo, 'title' | 'description'> = {
title: "Hey",
description: "foobar",
completed: false,
}
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
todo.completed = true // OK
풀이법
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [key in K]: T[key];
} & {
[key in keyof Omit<T, K>]: T[key];
}
- - type MyReadOnly2<T, K extends keyof T = keyof T> = { : 타입 파라미터를 객체 T와 T의 키로 이루어진 K로 정의한다.
- - & : key 부분에 대해서는 readonly를 선택적으로 줄 수 없기 때문에, readonly인 객체와 그렇지 않은 객체의 인터섹션 타입으로 구현.
- - { readonly [key in K]: T[key] } : readonly로 정의되는 부분은 명시되어 있는 K로 이루어진 프로퍼티들이 된다.
- - { pkey in keyof Omit<T, K>]: T[key] } : readonly가 아닌 부분은 명시되지 않은 부분으로 이루어진 키로 된 프로퍼티다.
이상의 논리를 따라가면 MyReadonly를 이해할 수 있다.
반응형