Skip to content

Instantly share code, notes, and snippets.

@greatertomi
Created May 22, 2024 23:05
Show Gist options
  • Save greatertomi/ca1983eb4884ea5f319a6b9fcb5452ae to your computer and use it in GitHub Desktop.
Save greatertomi/ca1983eb4884ea5f319a6b9fcb5452ae to your computer and use it in GitHub Desktop.
/* eslint-disable @typescript-eslint/no-explicit-any */
type DefaultValue<T> = T extends Function ? never : T extends object ? { [K in keyof T]: DefaultValue<T[K]> } : T;
export const createDefaultFormValues = <T extends Record<string, any>>(data?: T): DefaultValue<T> => {
if (!data) {
return {} as DefaultValue<T>;
}
const result: any = {};
Object.keys(data).forEach((key) => {
if (data[key] !== null && typeof data[key] === 'object' && Object.prototype.hasOwnProperty.call(data, key)) {
result[key] = createDefaultFormValues(data[key] as Record<string, unknown>);
} else {
result[key] = typeof data[key] === 'boolean' ? false : data[key] ?? '';
}
});
return result as DefaultValue<T>;
};
@mosidrum
Copy link

mosidrum commented May 23, 2024

Generic is powerful, I need to know it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment