Created
July 24, 2023 03:14
-
-
Save ryangoree/a0084a32962baa70a5ae48985628ac85 to your computer and use it in GitHub Desktop.
Deep convert function with converted types
This file contains 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
type Converted<T, TOriginal, TNew> = T extends TOriginal | |
? TNew | |
: T extends Array<infer U> | |
? Converted<U, TOriginal, TNew>[] | |
: T extends object | |
? { [K in keyof T]: Converted<T[K], TOriginal, TNew> } | |
: T; | |
function convert<T, TOriginal, TNew>( | |
value: T, | |
predicateFn: (value: any) => value is TOriginal, | |
converterFn: (value: TOriginal) => TNew, | |
): Converted<T, TOriginal, TNew> { | |
if (predicateFn(value)) { | |
return converterFn(value) as Converted<T, TOriginal, TNew>; | |
} | |
if (Array.isArray(value)) { | |
return value.map((item) => | |
convert(item, predicateFn, converterFn), | |
) as Converted<T, TOriginal, TNew>; | |
} | |
if (value && typeof value === "object") { | |
return Object.fromEntries( | |
Object.entries(value).map(([key, value]) => [ | |
key, | |
convert(value, predicateFn, converterFn), | |
]), | |
) as Converted<T, TOriginal, TNew>; | |
} | |
return value as Converted<T, TOriginal, TNew>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment