Skip to content

Instantly share code, notes, and snippets.

@angeloashmore
Created December 7, 2022 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angeloashmore/c9b0bc643a700164581222441c2225d3 to your computer and use it in GitHub Desktop.
Save angeloashmore/c9b0bc643a700164581222441c2225d3 to your computer and use it in GitHub Desktop.
`OmitNested` - A TypeScript type that omits nested object properties using dot notion.
type AppendDotPathSegment<
TPath extends string,
TSegment extends string,
> = TPath extends "" ? TSegment : `${TPath}.${TSegment}`;
type AnyFunction = (...args: any[]) => any;
type Primitives =
| boolean
| string
| number
| symbol
| unknown[]
| null
| undefined
| void
| AnyFunction;
type AllObjDotPaths<TObj, TPath extends string = ""> = TObj extends Primitives
? TPath
: {
[P in keyof TObj]: P extends string
?
| AppendDotPathSegment<TPath, P>
| AllObjDotPaths<TObj[P], AppendDotPathSegment<TPath, P>>
: TPath;
}[keyof TObj];
type RecursiveOmitNested<
TObj,
TOmitPath extends string,
TPath extends string = "",
> = TObj extends Primitives
? TObj
: {
[P in keyof TObj as P extends string
? AppendDotPathSegment<TPath, P> extends TOmitPath
? never
: P
: never]: P extends string
? RecursiveOmitNested<
TObj[P],
TOmitPath,
AppendDotPathSegment<TPath, P>
>
: TObj[P];
};
export type OmitNested<
TObj,
TOmitPath extends AllObjDotPaths<TObj>,
> = RecursiveOmitNested<TObj, TOmitPath>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment