structuredClone() not available in TypeScript

Viewed 11648

I'm running node.js v17.2.0 and TypeScript v4.5.4. I'm trying to use structuredClone() on a Map, and it doesn't seem to be working. ES2021 is targeted in tsconfig.json, and included in lib. Is this function just plain not available in TypeScript? Is there something else I need to include to get it?

@types/node is also installed, and I've made sure that it works in node.js environment.

structuredClone working in node.js environment

2 Answers

structuredClone is now present in @types/node v17.0.29:

 npm i --save-dev @types/node@17.0.29

structuredClone will be available in lib.dom of TypeScript v4.7 (as of 2022-05-19 it is currently in beta, but will be out soon). You can see where structuredClone was added to TypeScript here.

If you need to add it to your project temporarily until you can upgrade TypeScript, you can do that by putting the following definitions from the commit linked above into a structuredClone.d.ts file in your project (the base name doesn't matter, but the .d.ts does):

interface WindowOrWorkerGlobalScope {
    structuredClone(value: any, options?: StructuredSerializeOptions): any;
}
declare function structuredClone( value: any, options?: StructuredSerializeOptions): any;

(StructuredSerializeOptions is already defined by lib.dom.d.ts for postMessage, so we don't need to add it.)

Then just remove that file when you've upgraded later.

Related