Last active
July 8, 2022 16:11
-
-
Save sunnyy02/2477458d4d1c08bde8cc06cd8f56702e to your computer and use it in GitHub Desktop.
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
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; | |
} | |
} |
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
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])