From 067ef4eb0bb461bbd2bc882f9ce697c34f5ee18d Mon Sep 17 00:00:00 2001 From: sinclair Date: Mon, 20 Nov 2023 03:33:54 +0900 Subject: [PATCH] Clone Date and Uint8Array types --- src/typebox.ts | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/typebox.ts b/src/typebox.ts index bb6c50bf4..549041562 100644 --- a/src/typebox.ts +++ b/src/typebox.ts @@ -1087,6 +1087,14 @@ export namespace ValueGuard { export function IsBoolean(value: unknown): value is boolean { return typeof value === 'boolean' } + /** Returns true if this value is a Date object */ + export function IsDate(value: unknown): value is Date { + return value instanceof globalThis.Date + } + /** Returns true if this value is a function */ + export function IsFunction(value: unknown): value is Function { + return typeof value === 'function' + } /** Returns true if this value is null */ export function IsNull(value: unknown): value is null { return value === null @@ -1103,6 +1111,10 @@ export namespace ValueGuard { export function IsString(value: unknown): value is string { return typeof value === 'string' } + /** Returns true if this value is a Uint8Array */ + export function IsUint8Array(value: unknown): value is Uint8Array { + return value instanceof globalThis.Uint8Array + } /** Returns true if this value is undefined */ export function IsUndefined(value: unknown): value is undefined { return value === undefined @@ -2287,19 +2299,29 @@ export namespace TypeExtends { // -------------------------------------------------------------------------- /** Specialized Clone for Types */ export namespace TypeClone { + function ArrayType(value: unknown[]) { + return (value as any).map((value: unknown) => Visit(value as any)) + } + function DateType(value: Date) { + return new Date(value.getTime()) + } + function Uint8ArrayType(value: Uint8Array) { + return new Uint8Array(value) + } function ObjectType(value: Record) { const clonedProperties = Object.getOwnPropertyNames(value).reduce((acc, key) => ({ ...acc, [key]: Visit(value[key]) }), {}) const clonedSymbols = Object.getOwnPropertySymbols(value).reduce((acc, key) => ({ ...acc, [key]: Visit(value[key as any]) }), {}) return { ...clonedProperties, ...clonedSymbols } } - function ArrayType(value: unknown[]) { - return (value as any).map((value: unknown) => Visit(value as any)) - } function Visit(value: unknown): any { // prettier-ignore - return ValueGuard.IsArray(value) ? ArrayType(value) : + return ( + ValueGuard.IsArray(value) ? ArrayType(value) : + ValueGuard.IsDate(value) ? DateType(value) : + ValueGuard.IsUint8Array(value) ? Uint8ArrayType(value) : ValueGuard.IsObject(value) ? ObjectType(value) : value + ) } /** Clones a Rest */ export function Rest(schemas: [...T]): T {