Skip to content

Instantly share code, notes, and snippets.

@juliencrn
Created February 2, 2025 09:38
Show Gist options
  • Save juliencrn/1123d03a8049d8df9662df372fdfae29 to your computer and use it in GitHub Desktop.
Save juliencrn/1123d03a8049d8df9662df372fdfae29 to your computer and use it in GitHub Desktop.
Extends a type recursively
/**
* Extends a type recursively.
*
* @template T - The base recursive type to be extended.
* @template Ext - An additional set of properties to be merged into the type.
* @template Key - The key of the recursive property in T.
*
* @example
* ```ts
* type Node = {
* label: string;
* nodes: Node[];
* };
*
* type NodeWithId = ExtendRecursive<Node, { id: string }, "nodes">;
*
* // NodeWithId is equivalent to:
* // {
* // label: string;
* // id: string;
* // nodes: NodeWithId[];
* // }
* ```
*/
export type ExtendRecursive<
T extends Record<string, unknown>,
Ext extends Record<string, unknown>,
Key extends keyof T
> = Ext &
Omit<T, Key> & {
[K in Key]: ExtendRecursive<T, Ext, Key>[];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment