Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Created July 24, 2023 03:14
Show Gist options
  • Save ryangoree/a0084a32962baa70a5ae48985628ac85 to your computer and use it in GitHub Desktop.
Save ryangoree/a0084a32962baa70a5ae48985628ac85 to your computer and use it in GitHub Desktop.
Deep convert function with converted types
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