Skip to content

Instantly share code, notes, and snippets.

@sunnyy02
Last active July 8, 2022 16:11
Show Gist options
  • Save sunnyy02/2477458d4d1c08bde8cc06cd8f56702e to your computer and use it in GitHub Desktop.
Save sunnyy02/2477458d4d1c08bde8cc06cd8f56702e to your computer and use it in GitHub Desktop.
export class cloneable {
public static deepCopy<T>(source: T): T {
return Array.isArray(source)
? source.map(item => this.deepCopy(item))
: source instanceof Date
? new Date(source.getTime())
: source && typeof source === 'object'
? Object.getOwnPropertyNames(source).reduce((o, prop) => {
Object.defineProperty(o, prop, Object.getOwnPropertyDescriptor(source, prop)!);
o[prop] = this.deepCopy((source as { [key: string]: any })[prop]);
return o;
}, Object.create(Object.getPrototypeOf(source)))
: source as T;
}
}
@Neander64
Copy link

I got some TS errors (due to the version, i guess), which can be fixed like that
- TS2345 on Object.defineProperty(o, prop, Object.getOwnPropertyDescriptor(source, prop))
==> Object.defineProperty(o, prop, Object.getOwnPropertyDescriptor(source, prop)!)
- TS7053 on o[prop] = this.deepCopy(source[prop])
==> o[prop] = this.deepCopy((source as { [key: string]: any })[prop])

@sunnyy02
Copy link
Author

sunnyy02 commented Oct 3, 2021

I got some TS errors (due to the version, i guess), which can be fixed like that - TS2345 on Object.defineProperty(o, prop, Object.getOwnPropertyDescriptor(source, prop)) ==> Object.defineProperty(o, prop, Object.getOwnPropertyDescriptor(source, prop)!) - TS7053 on o[prop] = this.deepCopy(source[prop]) ==> o[prop] = this.deepCopy((source as { [key: string]: any })[prop])

You are right @Neander64, it is due to typescript version 4.1, the type checking is stricker....

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