Created
July 30, 2018 10:40
-
-
Save erikvullings/84412f727d3a86aa483f7a6f8feac807 to your computer and use it in GitHub Desktop.
Deep copy or clone in TypeScript
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
/** | |
* 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 | |
*/ | |
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