Linter · Rules
unicorn/prefer-structured-clone
Require structuredClone() for deep clones
JSON.parse(JSON.stringify(value)) turns a Date into a string, drops undefined, turns a Map or Set into {}, and throws on an object that refers to itself. structuredClone() is built in and copies all of these correctly, so you don't need a library function such as lodash's cloneDeep either.
Configure
Off by default. To turn it on:
[lint.rules]
"unicorn/prefer-structured-clone" = "error" # or "warn"
Every option, set to its default:
[lint.rules]
"unicorn/prefer-structured-clone" = ["error", {
functions = ["cloneDeep", "utils.clone"],
}]
Examples
Reported:
const draft = JSON.parse(JSON.stringify(settings));
const backup = _.cloneDeep(settings);
Not reported:
const draft = structuredClone(settings);
Options
| Option | Default | What it does |
|---|---|---|
functions | ["cloneDeep", "utils.clone"] | Names of functions to report. The list replaces the default. |
A name with a dot, such as utils.clone, only matches that object and method. A name without a dot matches a call to that function, and a method with that name on any object.
const draft = deepCopy(settings);
const backup = _.cloneDeep(settings);
When not to use it
structuredClone() throws on functions and DOM nodes, and the copy of a class instance is a plain object. If you clone values like that, keep your own function.