Closed
Description
structuredClone
についてこの型定義ライブラリでオーバーライドされていると便利かなと思うのですがいかがでしょうか?標準ライブラリのそれは今の所<T = any>(val: T, options?: StructuredSerializeOptions): T
というシグネチャになっており、うっかりすると実行時エラーを引き起こしそうです (例えば殆どのクラスはコンストラクタの情報を暗に持つためシリアライズできず、例外が起きます)。
提案するだけでは忍びないので実際にたたき台を作ってみました。継承が保存されずに親クラスに弱化されることに注意すると読みやすいと思います。
type StructuredCloneOutput<T> = T extends never
? never
: /* T extends EvalError // TS is not nominal...
// ? EvalError
:*/ T extends RangeError
? RangeError
: T extends ReferenceError
? ReferenceError
: T extends SyntaxError
? SyntaxError
: T extends TypeError
? TypeError
: T extends URIError
? URIError
: /*
T extends AggregateError
? AggregateError
:
*/
T extends DOMException
? DOMException
:
T extends Error
? Error // weaken (constructor)
: T extends boolean
? T // リテラル型
: T extends string
? T // リテラル型
: T extends [...any]
? T
: T extends Array<infer R>
? Array<R> // weaken (constructor)
: T extends null
? null
: T extends undefined
? undefined
: T extends Map<infer K, infer V>
? Map<K, V>
: T extends Set<infer E>
? Set<E>
: T extends number
? number
: T extends bigint
? T // literal
: T extends number
? T
: T extends symbol
? never // symbol cannot be cloned
: T extends Boolean
? Boolean
: T extends String
? String
: T extends Date
? Date
: T extends RegExp
? RegExp
: T extends Blob
? Blob
: T extends File
? File
: T extends FileList
? FileList
: T extends ArrayBuffer
? ArrayBuffer
: T extends Int8Array
? Int8Array // weaken (constructor)
: T extends Int16Array
? Int16Array // weaken (constructor)
: T extends Int32Array
? Int32Array // weaken (constructor)
: T extends BigInt64Array
? BigInt64Array // weaken (constructor)
: T extends Uint8Array
? Uint8Array // weaken (constructor)
: T extends Uint16Array
? Uint16Array // weaken (constructor)
: T extends Uint32Array
? Uint32Array // weaken (constructor)
: T extends BigUint64Array
? BigUint64Array // weaken (constructor)
: T extends Float32Array
? Float32Array // weaken (constructor)
: T extends Float64Array
? Float64Array // weaken (constructor)
: T extends Uint8ClampedArray
? Uint8ClampedArray // weaken (constructor)
: T extends DataView
? DataView
: T extends ImageBitmap
? ImageBitmap
: T extends ImageData
? ImageData
: T extends Function
? never
: T extends object
? { [K in keyof T]: StructuredCloneOutput<T[K]> } // value is writable
: never // T is symbol, it is not structured-cloneable
declare function structuredClone<T>(val: T, options?: StructuredSerializeOptions): StructuredCloneOutput<T>;