-
-
Save fabrianibrahim/5ee9bdfdbd98a19ecf8cea1efab8935a to your computer and use it in GitHub Desktop.
Deep copy or clone in TypeScript
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
| /** | |
| * 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