Skip to content

Instantly share code, notes, and snippets.

@fabrianibrahim
Forked from erikvullings/deep-copy.ts
Created November 8, 2022 22:12
Show Gist options
  • Select an option

  • Save fabrianibrahim/5ee9bdfdbd98a19ecf8cea1efab8935a to your computer and use it in GitHub Desktop.

Select an option

Save fabrianibrahim/5ee9bdfdbd98a19ecf8cea1efab8935a to your computer and use it in GitHub Desktop.
Deep copy or clone in TypeScript
/**
* Deep copy function for TypeScript.
* @param T Generic type of target/copied value.
* @param target Target value to be copied.
* @see Source project, ts-deepcopy https://github.com/ykdr2017/ts-deepcopy
* @see Code pen https://codepen.io/erikvullings/pen/ejyBYg
*/
export const deepCopy = <T>(target: T): T => {
if (target === null) {
return target;
}
if (target instanceof Date) {
return new Date(target.getTime()) as any;
}
if (target instanceof Array) {
const cp = [] as any[];
(target as any[]).forEach((v) => { cp.push(v); });
return cp.map((n: any) => deepCopy<any>(n)) as any;
}
if (typeof target === 'object' && target !== {}) {
const cp = { ...(target as { [key: string]: any }) } as { [key: string]: any };
Object.keys(cp).forEach(k => {
cp[k] = deepCopy<any>(cp[k]);
});
return cp as T;
}
return target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment