UNPKG

1.96 kBTypeScriptView Raw
1import type {TypedArray} from './typed-array';
2import type {FindGlobalInstanceType} from './find-global-type';
3
4type StructuredCloneablePrimitive =
5 | string
6 | number
7 | bigint
8 | boolean
9 | null
10 | undefined
11 | Boolean
12 | Number
13 | String;
14
15type StructuredCloneableData =
16 | ArrayBuffer
17 | DataView
18 | Date
19 | Error
20 | RegExp
21 | TypedArray
22 | FindGlobalInstanceType<
23 // DOM or Node types
24 | 'Blob'
25 | 'File'
26 // DOM exclusive types
27 | 'AudioData'
28 | 'CropTarget'
29 | 'CryptoKey'
30 | 'DOMException'
31 | 'DOMMatrix'
32 | 'DOMMatrixReadOnly'
33 | 'DOMPoint'
34 | 'DOMPointReadOnly'
35 | 'DOMQuad'
36 | 'DOMRect'
37 | 'DOMRectReadOnly'
38 | 'FileList'
39 | 'FileSystemDirectoryHandle'
40 | 'FileSystemFileHandle'
41 | 'FileSystemHandle'
42 | 'GPUCompilationInfo'
43 | 'GPUCompilationMessage'
44 | 'ImageBitmap'
45 | 'ImageData'
46 | 'RTCCertificate'
47 | 'VideoFrame'
48 >;
49
50type StructuredCloneableCollection =
51 | readonly StructuredCloneable[]
52 | {readonly [key: string]: StructuredCloneable; readonly [key: number]: StructuredCloneable}
53 | ReadonlyMap<StructuredCloneable, StructuredCloneable>
54 | ReadonlySet<StructuredCloneable>;
55
56/**
57Matches a value that can be losslessly cloned using `structuredClone`.
58
59Note:
60- Custom error types will be cloned as the base `Error` type
61
62@see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
63
64@example
65```
66import type {StructuredCloneable} from 'type-fest';
67
68class CustomClass {}
69
70// @ts-expect-error
71const error: StructuredCloneable = {
72 custom: new CustomClass(),
73};
74
75structuredClone(error);
76//=> {custom: {}}
77
78const good: StructuredCloneable = {
79 number: 3,
80 date: new Date(),
81 map: new Map<string, number>(),
82}
83
84good.map.set('key', 1);
85
86structuredClone(good);
87//=> {number: 3, date: Date(2022-10-17 22:22:35.920), map: Map {'key' -> 1}}
88```
89
90@category Structured clone
91*/
92export type StructuredCloneable = StructuredCloneablePrimitive | StructuredCloneableData | StructuredCloneableCollection;