[Typescript Challenges] 16. Medium - Omit
Implement the built-in Omit<T, K>
generic without using it.
Constructs a type by picking all properties from T
and then removing K
For example
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = MyOmit<Todo, 'description' | 'title'>
const todo: TodoPreview = {
completed: false,
}
Have to use remapping keywrod as
, [P in keyof T as P extends K ? never: P]
, cannot just do [P in keyof T extends K...]
/* _____________ Your Code Here _____________ */
type MyOmit<T, K> = {
[P in keyof T as P extends K ? never: P]: T[P]
}
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type x = MyOmit<Todo, 'description'>
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
}