Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: respect Optional in Transform.Encode/Decode #783

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/value/transform/decode.ts
Expand Up @@ -52,7 +52,7 @@ import { IsStandardObject, IsArray, IsValueType } from '../guard/index'
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
import { IsTransform, IsSchema } from '../../type/guard/type'
import { IsTransform, IsSchema, IsOptional } from '../../type/guard/type'
// ------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------
Expand All @@ -73,7 +73,13 @@ export class TransformDecodeError extends TypeBoxError {
// prettier-ignore
function Default(schema: TSchema, value: any) {
try {
return IsTransform(schema) ? schema[TransformKind].Decode(value) : value
if (IsTransform(schema)) {
if (IsOptional(schema) && value === undefined) {
return undefined
}
return schema[TransformKind].Decode(value)
}
return value
} catch (error) {
throw new TransformDecodeError(schema, value, error)
}
Expand Down
10 changes: 8 additions & 2 deletions src/value/transform/encode.ts
Expand Up @@ -52,7 +52,7 @@ import { IsStandardObject, IsArray, IsValueType } from '../guard/index'
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
import { IsTransform, IsSchema } from '../../type/guard/type'
import { IsTransform, IsSchema, IsOptional } from '../../type/guard/type'
// ------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------
Expand All @@ -72,7 +72,13 @@ export class TransformEncodeError extends TypeBoxError {
// prettier-ignore
function Default(schema: TSchema, value: any) {
try {
return IsTransform(schema) ? schema[TransformKind].Encode(value) : value
if (IsTransform(schema)) {
if (IsOptional(schema) && value === undefined) {
return undefined
}
return schema[TransformKind].Encode(value)
}
return value
} catch (error) {
throw new TransformEncodeError(schema, value, error)
}
Expand Down