Readonly 2 - medium - [Type Challenge]

강성훈·2023년 1월 25일
0

type-challenges

목록 보기
16/20
post-thumbnail

by Anthony Fu @antfu

문제

T에서 K 프로퍼티만 읽기 전용으로 설정해 새로운 오브젝트 타입을 만드는 제네릭 MyReadonly2<T, K>를 구현하세요.
K가 주어지지 않으면 단순히 Readonly<T>처럼 모든 프로퍼티를 읽기 전용으로 설정해야 합니다.

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

솔루션

2개의 타입변수를 받을 것입니다. 단 2번째 변수는 첫번 째 타입안에 존재하여야 할 것

type MyReadonly2<T, U extends keyof T> = ??;

U는 전부 readonly 로 만들어줍니다.

type MyReadonly2<T, U extends keyof T> = {[u in U]: U[u]}

그리고 T에서 U를 제외한 값을 readonly 없이 만든 뒤 두개를 합쳐줍니다.

type MyReadonly2<T, U extends keyof T> = {
  readonly [u in U]: T[u];
} & {
  [t in Exclude<keyof T, U>]: T[t];
};
profile
고등학생 주니어 개발자

0개의 댓글