Created
March 13, 2025 16:55
-
-
Save claytonchew/9ca60edc0682fdc4bea5fe64c36c4f30 to your computer and use it in GitHub Desktop.
Typescript utility for simplifying an object or array type recursively to its most basic representation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Simplifies an object or array type recursively to its most basic representation. | |
| * | |
| * @example | |
| * // Complex nested type | |
| * type Complex = Array< | |
| * SerializeObject<{ | |
| * data: Array<SerializeObject<{ date: number } & { name: string } & { amount: number }>>; | |
| * metadata: { date: Date } & { name: string } & { amount: number }; | |
| * }> | |
| * >; | |
| * | |
| * // Using Simplify to flatten the structure | |
| * type Simple = Simplify<Complex>; | |
| * // Result: { | |
| * // data: { date: string; name: string; amount: number }[]; | |
| * // metadata: { date: string; name: string; amount: number }; | |
| * // }[] | |
| */ | |
| export type Simplify<T> = | |
| T extends Array<infer Shape> | |
| ? Array<Simplify<Shape>> | |
| : T extends Date | |
| ? Date | |
| : T extends object | |
| ? { | |
| [K in keyof T]: Simplify<T[K]>; | |
| } | |
| : T; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment