Last active
June 26, 2021 17:59
-
-
Save eczn/d0a250daa882e238127bb2b134ecd436 to your computer and use it in GitHub Desktop.
deep clone
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
| type Fn = (...args: unknown[]) => unknown; | |
| // 取出 T 中静态 keys | |
| type StaticKeys<T> = { | |
| [K in keyof T]: T[K] extends Fn ? never : K | |
| }[keyof T] | |
| // 去除 T 里面的函数 | |
| type StaticObject<T> = Pick<T, StaticKeys<T>> | |
| /** | |
| * 深度拷贝 | |
| * @param obj | |
| * @returns | |
| */ | |
| export function cloneObj<T>(obj: T): StaticObject<T> { | |
| if (typeof obj !== 'object') return obj; | |
| const keys = Object.keys(obj) as Array<keyof T>; | |
| const cloned: any = {}; // ts 这里没法定义 | |
| keys.forEach(k => { | |
| const value = obj[k]; | |
| if (typeof value === 'object') { | |
| cloned[k] = cloneObj(obj[k]); | |
| } else { | |
| cloned[k] = obj[k]; | |
| } | |
| }); | |
| return cloned; | |
| } | |
| console.log( | |
| cloneObj({ a: { b: { c: 123 } } }).a.b | |
| ); | |
| console.log( | |
| cloneObj([{ a: { b: { c: 123 } } }])[0].a.b | |
| ); | |
| console.log( | |
| cloneObj(new class { a = 1; b = 2; c = 3 }) | |
| ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment