Language/Typescript
타입챌린지 : 2852-OmitByType (medium)
hsloth
2023. 5. 20. 12:55
이 글은 제가 타입챌린지를 하면서 해석한 내용을 적는 글입니다. 틀린 내용이 있으면 댓글 달아주시면 감사하겠습니다.
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
T에서 U라는 타입을 가진 속성을 제외하여 리턴하는 타입이다.
와... 정말 간단하다. 지금까지 타입챌린지를 하나하나 여기까지 풀었던 사람이라면 진짜 1초컷 날 만한 문제다.
type OmitByType<T, U> = {
[P in keyof T as T[P] extends U ? never : P]: T[P]
}
type A = OmitByType<Model, boolean>
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
interface Model {
name: string
count: number
isReadonly: boolean
isEnable: boolean
}
type cases = [
Expect<Equal<OmitByType<Model, boolean>, { name: string; count: number }>>,
Expect<Equal<OmitByType<Model, string>, { count: number; isReadonly: boolean; isEnable: boolean }>>,
Expect<Equal<OmitByType<Model, number>, { name: string; isReadonly: boolean; isEnable: boolean }>>,
]
[P in keyof T as T[P] extends U ? never : P] : T의 키값을 P라고 할때, T[P](T에 키값을 대입한 값, 즉, T의 P속성의 밸류값)가 U라면, never를 리턴하고, 아니라면 P를 그대로 리턴한다.