Deep Omit
Less than 1 minuteTC-Medium
Deep Omit
Problem
Implement a type DeepOmit<T, K>, which omits the property K (a dot-separated path) from nested objects.
type T = {
a: string
b: {
c: string
d: {
e: string
f: string
}
}
}
type T0 = DeepOmit<T, 'b'> // { a: string }
type T1 = DeepOmit<T, 'b.c'> // { a: string; b: { d: { e: string; f: string } } }
type T2 = DeepOmit<T, 'b.d.e'> // { a: string; b: { c: string; d: { f: string } } }Solution
type DeepOmit<T, K extends string> =
K extends `${infer Head}.${infer Tail}`
? {
[P in keyof T]: P extends Head
? DeepOmit<T[P], Tail>
: T[P]
}
: Omit<T, K>How it works:
- Check if
Kcontains a.separator. - If yes, split into
Head(first segment) andTail(rest).- Keep all properties unchanged, except for
Head— recurse into its value withTail.
- Keep all properties unchanged, except for
- If no
., we are at the final key — use standardOmit<T, K>to remove it.
Key Takeaways
- Parsing a dot-separated path with
K extends `${infer Head}.${infer Tail}`is the standard recursive path-descent pattern. - The recursion matches the path segment-by-segment, delegating the omit to the leaf level.
- At the leaf,
Omit<T, K>handles the actual removal.
