728x90
문제
T
에서 K
프로퍼티만 제거해 새로운 오브젝트 타입을 만드는 내장 제네릭 Omit<T, K>
를 이를 사용하지 않고 구현하세요.
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = MyOmit<Todo, 'description' | 'title'>
const todo: TodoPreview = {
completed: false,
}
cases
type cases = [
Expect<Equal<Expected1, MyOmit<Todo, 'description'>>>,
Expect<Equal<Expected2, MyOmit<Todo, 'description' | 'completed'>>>,
]
// @ts-expect-error
type error = MyOmit<Todo, 'description' | 'invalid'>
interface Todo {
title: string
description: string
completed: boolean
}
interface Expected1 {
title: string
completed: boolean
}
interface Expected2 {
title: string
}
정답
type MyOmit<T, K> = {
[key in keyof T as key extends K ? never : key]: T[key]
}
풀이
조건
- K에 포함된 값은 T에서 제거한다.
해설
- T 의 키 값을 가져오는 문법은 다음과 같다.
type MyOmit<T> = {
[key in keyof T]: T[key]
}
- 키 값에 조건을 걸어 확인하는 문법은 다음과 같다.
type MyOmit<T, K> = {
[key as key extends A ? true :false] : T[key]
}
1번과 2번을 조합해서 정답을 내면 다음과 같다.
type MyOmit<T, K> = {
[key in keyof T as key extends K ? never : key]: T[key]
}
오류나 개선점이 있다면 댓글 부탁드립니다.
728x90
'FE > type-challenge' 카테고리의 다른 글
9. DeepReadonly (1) | 2023.09.02 |
---|---|
8. Readonly2 (0) | 2023.09.01 |
2. ReturnType (0) | 2023.08.30 |
7544. ConstructTuple (0) | 2023.08.26 |
5360. Unique (0) | 2023.08.25 |